17 August, 2011

Creating a Cache Page Output Dependency in Asp.net

To create a cache page output dependency, call one of the following Response methods:
1) Response.AddCacheDependency
This makes the validity of a cached response dependent on a CacheDependency object.

In ASP.NET 2.0, developers are free to develop their own custom cache dependencies. The CacheDependency class allows for the creation of a custom cache dependency based on files, directories, or cache keys.
For example, the code below creates a new custom cache dependency based on a file called stuff.xml located in the root of the Web application:
System.Web.Caching.CacheDependency dep = new
System.Web.Caching.CacheDependency(Server.MapPath("stuff.xml"));
Response.AddCacheDependency(dep);
Cache.Insert("key", "value");

In this scenario, when the stuff.xml file changes, the cached item is invalidated.
It is also possible to create a custom cache dependency using cache keys. Using this method, the removal of the cache key will invalidate the cached data. The following example illustrates this:
// insert a value into cache that will serve
// as the cache key
Cache["CacheKey"] = "something";

// create an array of cache keys
string[] keys = new String[1];
keys[0] = "CacheKey";

CacheDependency dep = new CacheDependency(null, keys);

// insert an item into cache with a dependency on
// the above CacheDependency
Cache.Insert("Key", "Value", dep);
  To invalidate the item that was inserted above, simply remove the item that was inserted into cache to act as the cache key.
// Remove the cache item that serves as the cache key
Cache.Remove("CacheKey");
 

2) Response.AddCacheItemDependency and Response.AddCacheItemDependencies
These make the validity of a cached response dependent on one or more other
items in the cache.


When you add pages to the output cache, the page will be removed when the amount of time you specify in the expiration policy has passed. There are times when you want a page, or versions of a page, to be removed from the output cache before it has expired. For example, if your page displays volatile data, such as a stock price or a temperature, the page will display incorrect information if the data is updated before the page expires.
To address this issue, ASP.NET provides the HttpResponse.AddCacheItemDependency and HttpResponse.AddCacheItemDependencies methods, which allow you to cache page output that is dependent upon an item in the Cache object (associated with the application that the page belongs to).

The AddCacheItemDependency method allows you to create a relationship between the page and a single item in the Cache, while the AddCacheItemDependencies method allows you to create relationship between the page and an array of Cache items. When any of the items upon which the page is dependent change or are removed from the application Cache, the page output is invalidated and removed from the output cache. 

Note   You cannot use these methods from a Web Forms user control.


To make cached page output dependent upon a Cache item
  1. Specify the settings for caching page output either declaratively or programmatically.
  2. In the code-declaration block or the code-behind file for the page, add an item to your Web application's Cache object using the Cache.Item property, the Cache.Addmethod, or the Cache.Insert method.
  3. In the code-declaration block or the code-behind file for the page, use Response object syntax to call the AddCacheItemDependency or AddCacheItemDependenciesmethod, specifying the cached item or items upon which the page is dependent.
The following example assumes that an application contains a temperature component. The component uses the Cache.Insert method to place a temperature into the application Cache. 
Cache.Insert("Temperature.CurrentTemperature", currentTemperature);

The following page code, found in a code-declaration block or code-behind file, gets the current temperature stored in the Cache, converts it to a string, and then displays it. It then makes its output cache version dependent upon the Temperature.CurrentTemperature key. From this point forward, when the temperature component updates the temperature, the page version is flushed from the output cache. The page will be placed in the output cache again when it is subsequently requested.

int temperature = (int) Cache.Get("Temperature.CurrentTemperature");
LabelTemperature.Text = temperature.ToString();
Response.AddCacheItemDependency("Temperature.CurrentTemperature");

[Visual Basic]
Dim temperature as Integer
temperature = Cache.Get("Temperature.CurrentTemperature")
LabelTemperature.Text = temperature.ToString()
Response.AddCacheItemDependency("Temperature.CurrentTemperature")

3) Response.AddFileDependency and Response.AddFileDependencies
These make the validity of a cached response dependent on one or more files.


At times you might want to remove a page from the output cache when a file changes. For example, you might have a page that gets its contents from a process-intensive report that produces an XML file as output. The page needs to be reprocessed only if the XML file changes. To limit reprocessing to just those times when it is necessary, you can use the make the page's cache policy dependent on a single file. If required, you can make the cached page dependent on more than one file.

To make cached page output dependent upon a file

  1. Specify the settings for caching page output either declaratively or programmatically.
  2. In the page code, call the AddFileDependency method. As the method's filename parameter, pass the path of the file on which you are creating a dependency.
The following code example sets a file dependency on the TextFile1.txt file. When the file changes, the page output will be removed from the cache.

protected void Page_Load(object sender, EventArgs e)
{
    string fileDependencyPath = Server.MapPath("TextFile1.txt");
    Response.AddFileDependency(fileDependencyPath);

    // Set additional properties to enable caching.
    Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
    Response.Cache.SetCacheability(HttpCacheability.Public);
    Response.Cache.SetValidUntilExpires(true);
}

To make cached page output dependent on a group of files

  1. Specify the settings for caching page output either declaratively or programmatically.
  2. In the page code, create a String array or an ArrayList that contains the paths of the files to make the page dependent on.
  3. Call the AddFileDependencies method and as the filenames parameter, pass the array.
The following code example creates a string array of the file paths for the TextFile1.txt and XMLFile1.xml files and makes the page output dependent on the two files. If either one of the files is modified, the page output will be removed from the cache.

protected void Page_Load(object sender, EventArgs e)
{
    string[] fileDependencies;
    string fileDependency1 = Server.MapPath("TextFile1.txt");
    string fileDependency2 = Server.MapPath("XMLFile1.xml");
    fileDependencies = new String[] { fileDependency1, 
        fileDependency2 };
    Response.AddFileDependencies(fileDependencies);
}

No comments:

Post a Comment