練習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);
}
}