Enterprise Library 2.0 Hands On Lab 翻译(10):缓存应用程序块(二)
2006-10-09 00:24:00
版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://terrylee.blog.51cto.com/342737/67641 |
练习2:持久缓存
该练习将示范如何持久缓存。
第一步
打开EmployeeBrowser.sln 项目,默认的安装路径应该为C:\Program Files\Microsoft Enterprise Library January 2006\labs\cs\Caching\exercises\ex02\begin,并编译。
第二步 实现离线缓存
1.在解决方案管理器中选择EmployeeServices.cs文件,选择View | Code菜单命令并添加如下命名空间。
using Microsoft.Practices.EnterpriseLibrary.Caching.Expirations;2.定位到GetContactDetails方法,并添加如下代码。
public static EmployeesDataSet GetContactDetails()![]() { EmployeesDataSet dsEmployees = null;![]() // TODO: Add persistent caching with time-out![]() // Attempt to retrieve from cache![]() CacheManager cache = CacheFactory.GetCacheManager();![]() dsEmployees = (EmployeesDataSet)cache[CACHE_KEY];![]() // Retrieve from dataProvider if not in Cache and Online![]() if (dsEmployees == null && ConnectionManager.IsOnline)![]() {![]() EmployeeDataProvider dataProvider = new EmployeeDataProvider();![]() dsEmployees = dataProvider.GetEmployees();![]() // Expire in 2 days![]() AbsoluteTime expiry = new AbsoluteTime(new TimeSpan(2, 0, 0, 0));![]() cache.Add(CACHE_KEY, dsEmployees,![]() CacheItemPriority.High, null,![]() new ICacheItemExpiration[] { expiry });![]() }![]() return dsEmployees;![]() }3.修改方法GetEmployeePhoto为如下代码,即离线时不尝试去获取信息。
public static Bitmap GetEmployeePhoto(Guid employeeId)![]() { byte[] photoData = null;![]() // Attempt to retrieve from cache![]() CacheManager cache = CacheFactory.GetCacheManager();![]() photoData = (byte[])cache[employeeId.ToString()];![]() // TODO: Retrieve from dataProvider if not in Cache and Online![]() if (photoData == null && ConnectionManager.IsOnline)![]() {![]() EmployeeDataProvider dataProvider = new EmployeeDataProvider();![]() photoData = dataProvider.GetEmployeePhotoData(employeeId);![]() cache.Add(employeeId.ToString(), photoData);![]() }![]() // No data found.![]() if (photoData == null)![]() return null;![]() // Convert bytes to Bitmap![]() using (MemoryStream ms = new MemoryStream(photoData))![]() { return new Bitmap(ms); }![]() }第三步 配置持久缓存
1.在解决方案管理器中选择项目EnoughPI的配置文件App.config文件,选择View | Open With…菜单命令,选择Enterprise Library Configuration并单击OK按钮。
2.选择Caching Application Block | Cache Managers | Cache Manager节点,选择Action | New | Isolated Storage菜单命令。
3.设置属性PartitionName为EmployeeBrowser。 PartitionName允许多个缓存共享相同的物理存储位置。4.保存应用程序配置。
第四步 运行应用程序
1.选择Debug | Start Without Debugging菜单命令运行应用程序。浏览少量的雇员信息employees加载到缓存中,不要浏览所有的雇员信息。
2.在解决方案管理器中选择ConnectionManager.cs,选择View | Code菜单命令,在下面的代码中修改IsOnline属性的值。
static public bool IsOnline![]() {![]() get { return false; }![]() }3.选择Debug | Start Without Debugging菜单命令运行应用程序。现在应用程序处于离线状态并没有连接数据库。
4.关闭应用程序和Visual Studio.NET。
更多Enterprise Library的文章请参考《Enterprise Library系列文章》 本文出自 “TerryLee技术专栏” 博客,请务必保留此出处http://terrylee.blog.51cto.com/342737/67641 本文出自 51CTO.COM技术博客 |







EmployeesDataSet dsEmployees 
}
}
3
PartitionName
lihuijun
博客统计信息
热门文章
最新评论
友情链接