程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> 關於ASP.NET >> Enterprise Library 2.0 Hands On Lab 翻譯(10):緩存應用程序塊(二)

Enterprise Library 2.0 Hands On Lab 翻譯(10):緩存應用程序塊(二)

編輯:關於ASP.NET

練習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. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved