http://www.codeproject.com/aspnet/cachingaspnet/caching.zip
Introduction
The majority [if not all] of the pages in a dynamic website are dynamic. That is, pages that are created on user request. As we all know, dynamic web pages help to provide dynamic content, customized for the user requesting the page [ eg:. the user's home page] Dynamic pages also help provide dynamic content fetched from a changing data store without the need for the administrator to change the page content every time something changes in the data store [eg: Listing of books in a publisher's website ]. The disadvantage is the overhead in create.
To overcome this, some websites have page creation engines which create all pages in one go and save them as HTML pages which are then served to the users. But this will only help in scenarios where the page content is the same for all requests [user -independent] as in the second example above. The listing of books is the same irrespective of the user requesting the page. Even if there is provision for listing books category wise by providing different category ID values through the querystring, the page output for a Particular Category of Books Is The Same for All Users.
ASP.NET provides support for "caching" which will help us solve this problem to a great extend. It can cache [store in memory] the output generated by a page and will serve this cached content for future requests. And this is useful only in the second scenario described earlier, where the page content is the same for all requests [user-independent]. The caching feature is customizable in various ways and we will see how we can do that as we go through this article.
Caching a page
In Order to Cache a page's output, we need to specify an @outputcache Directive at the top of the page. The top of the page: <% @ outputcache duration = 5 VarybyParam = "none"%>%>
As You Can See, There Are Two Attributes To this Directive. They Are:
Duration -.. The time in seconds of how long the output should be cached After the specified duration has elapsed, the cached output will be removed and page content generated for the next request That output will again be cached for 10 seconds and the process repeats . VaryByParam -. This attribute is compulsory and specifies the querystring parameters to vary the cache In the above snippet, we have specified the VaryByParam attribute as None which means the page content to be served is the same regardless of the parameters passed through the querystring [ . see Example 1 in the sample download] If there are two requests to the same page with varying querystring parameters, eg: ... / PageCachingByParam.aspx id = 12 and ... / PageCachingByParam.aspx id = 15] and?? separate page content is generated for each of them, the directive should be: <% @ OutputCache Duration = 5 VaryByParam = "id"%> The page content for the two requests will each be cached for the time specified by the Duration attribute [see Example 2 in the sample download]. To specify multiple parameters, use semicolon to separate the parameter names. If we specify the VaryByParam attribute as *, the cached content is varied for all parameters passed through the querystring.
Some pages generate different content for different browsers In such cases, there is provision to vary the cached output for different browsers The @OutputCache directive has to be modified to:.. <% @ OutputCache Duration = 5 VaryByParam = "id" VaryByCustom = " Browser "%>
This Will Vary The Cached Output Not Only for the Browser But Also ITS Major Version. I., IE5, IE 6, Netscape 4, Netscape 6 Will All Get Different Cached Versions of The Output.
Caching page fragments
Sometimes we might want to cache just portions of a page. For example, we might have a header for our page which will have the same content for all users. There might be some text / image in the header which might change everyday. In that Case, We Will Want To Cache this Header for a duration of a day.
THE Solution Is To Put The Header Contents Into A User Control Content Should Be Cached. This Technique IS Called Fragment Caching.
To Specify That A User Control Should Be Cached, We Use the @outputcache Directive Just Like We buy it for the page.
<% @ Outputcache duration = 10 varybyparam = "none"%>
With the above directive, the user control content will be cached for the time specified by the Duration attribute [10 secs]. Regardless of the querystring parameters and browser type and / or version, the same cached output is served. [See Example 3 in The Download for a DemonStration].
Data caching
ASP.NET also supports caching of data as objects. We can store objects in memory and use them across various pages in our application. This feature is implemented using the Cache class. This cache has a lifetime equivalent to that of the application. Objects can BE Stored As Name Value Pairs in The Cache. A String Value Can Be Inserted Into The Cache As Follows: Cache ["Name"] = "Smitha";
The Stored String Value Can Be Retrieved Like this:
IF (Cache ["Name"]! = null) label1.text = cache ["name"]. Tostring ();
[See esample 4 for an illustration.]
To insert objects into the cache, the Add method or different versions of the Insert method of the Cache class can be used. These methods allow us to use the more powerful features provided by the Cache class. One of the overloads of the Insert method is Used as Follows:
Cache.insert ("Name", Strname, New CachedPependency (Server.mappath ("Name.txt"), DateTime.now.addminutes (2), Timespan.zero;
The first two parameters are the key and the object to be inserted. The third parameter is of type CacheDependency and helps us set a dependency of this value to the file named name.txt. So whenever this file changes, the value in the cache is removed. We can specify null to indicate no dependency. The fourth parameter specifies the time at which the value should be removed from cache. [See example 5 for an illustration.] The last parameter is the sliding expiration parameter which shows the time interval after Which the item is to be removed from the cache after its last accepted time.
. The cache automatically removes the least used items from memory, when system memory becomes low This process is called scavenging We can specify priority values for items we add to the cache so that some items are given more priority than others:. Cache.Insert ( "Name", strname, new cachedependency (server.mappath ("name.txt"), datetime.now.addminutes (2), timespan.zero, cacheitempriority.high, null;
The CacheItemPriority Enumeration Has Members To Set Various Priority Values. The cacheitempriority.high Assigns a priority level to an item so thing the item the cache.
Points of interest
If there are old ASP pages in your website which use the Response.Expires property to cache page output, they can be retained as such. ASP.NET supports this property as well. The Insert method of the Cache class will overwrite any existing item with the same key name. The CacheItemPriority.NotRemovable priority value can be used with Cache.Insert method to set the priority level of an item so that the item will not be removed from the cache during scavenging.
Conclusion
In this Article, I Have Tried to Provide An Overview of the Various Options Available for Caching In Asp.Net. ElaBorate Explanations and Details Have Not Been Provided to Keep The Article Short.
Fragment caching can be done in a nested fashion with child controls having caching enabled. How to do this has not been covered as I have not tried it out myself. So also various overloads of the Insert method of the Cache class has not been discussed here . I Hope this Article Will Be a Good Starting Point for the Readers to Explore Into The Details of A Wonderful Feature Available in Asp.net.