Enterprise Library 2.0 Hands On Lab 翻譯(10):緩存應用程序塊(二)
練習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系列文章》
Worktile,新一代簡單好用、體驗極致的團隊協同、項目管理工具,讓你和你的團隊隨時隨地一起工作。完全免費,現在就去了解一下吧。
https://worktile.com



浙公網安備 33010602011771號