How to use caching in ASP.Net

ASP.NET Caching:
 
ASP.NET provides two types of caching that you can use to create high-performance Web applications.
1.   The first is output caching, which allows you to store dynamic page and user control responses on any HTTP 1.1 cache-capable device in the output stream, from the originating server to the requesting browser. On subsequent requests, the page or user control code is not executed; the cached output is used to satisfy the request.
2.   The second type of caching is application data caching, which you can use to programmatically store arbitrary objects, such as application data, in server memory so that your application can save the time and resources it takes to recreate them.
To help you increase application performance in these situations, ASP.NET provides caching using two basic caching mechanisms. The first is application caching, which allows you to cache data you generate, such as a DataSet or a custom report business object. The second is page output caching, which saves the output of page processing and reuses the output instead of re-processing the page when a user requests the page again.
1.   Application Cache
The application cache provides a programmatic way for you to store arbitrary data in memory using key/value pairs.
2.   Page Output Cache
The page output cache stores the contents of a processed ASP.NET page in memory. This allows ASP.NET to send a page response to a client without going through the page processing lifecycle again. Page output caching is especially useful for pages that do not change often but require significant processing to create. Page caching can be configured individually for each page, or you can create cache profiles in the Web.config file, which allow you to define caching settings once and then use those settings with multiple pages.
Page output caching provides two models for page caching:
2.1.  Full page caching and partial page caching. Full page caching allows the entire contents of a page to be persisted to memory and used to fulfill client requests.
2.2.  Partial page caching allows parts of a page to be cached and other parts to be dynamic. For more information see Caching ASP.NET Pages. Partial page caching can work in two ways: control caching and post-cache substitution:
2.2.1.Control caching, also sometimes referred to as fragment caching, allows you to cache parts of the page output by including the information in a user control and then marking the user control as cacheable. This allows specific content within a page to be cached, while the overall page is not cached and therefore recreated each time. For example, if you create a page that displays largely dynamic content, such as stock information, but has sections that are static, such as weekly summaries, you can place the static sections in user controls and allow them to be cached.
2.2.2.         Post-cache substitution is the opposite. The page as a whole is cached, but fragments within the page are dynamic. For example, if you create a page that is static for set periods of time, you can set the entire page to be cached. If you added a Label control to the page that displayed the user’s name, the Label would stay the same for each page refresh and each user, showing the name of the user who requested that page before it was cached. However, with post-cache substitution, you can configure the page to be cached, but mark individual sections of the page as not cacheable. In this case, you could add your Labelcontrols to a non-cacheable section and they would be dynamically created for each user and page request. For more information, see Caching Portions of an ASP.NET Page.
 
Automatic Data Removal:

ASP.NET can remove data from the cache for one of these reasons:

·         Because memory on the server is low, a process known as scavenging.
·         Because the item in the cache has expired.
·         Because the item’s dependency changes.

To help you manage cached items, ASP.NET can notify your application when items are removed from the cache.

Scavenging

Scavenging is the process of deleting items from the cache when memory is scarce. Items are removed when they have not been accessed in some time or when items are marked as low priority when added to the cache. ASP.NET uses the CacheItemPriority object to determine which items to scavenge first. For more information see How to: Add Items to the Cache.

Expiration

In addition to scavenging, ASP.NET automatically removes items from the cache when they expire. When adding an item to the cache, you can set it to expire as described in the following table.

Expiration Type
Description
Sliding expiration
Specifies how long after an item was last accessed that it expires. For example, you can set an item to expire 20 minutes after it was last accessed in the cache.
Absolute expiration
Specifies that an item expires at a set time, regardless of how often it is accessed. For example, you can set an item to expire at 6:00 PM or after four hours.

Dependencies

You can configure an item’s lifetime in the cache be dependent on other application elements such as files or databases. When the element that a cache item depends on changes, ASP.NET removes the item from the cache. For example, if your Web site displays a report that the application creates from an XML file, you can place the report in the cache and configure it to have a dependency on the XML file. When the XML file changes, ASP.NET removes the report from the cache. When your code requests the report, the code first determines whether the report is in the cache, and if not, your code can recreate it. Therefore, an up-to-date version of the report is always available.

ASP.NET caching supports the dependencies described in the following table.

Dependency
Description
Key dependency
Items in the application cache are stored in key/value pairs. Key dependency allows an item to be dependent on the key of another item in the application cache. When the original item is removed, the item that has the key dependency is also removed. For example, you could add a cache item named ReportsValid, and then cache several reports that are dependent on theReportsValid key. When the ReportsValid item is removed, all the dependent cached reports are likewise removed from the cache.
File dependency
An item in the cache is dependent on an external file. If the file is modified or deleted, the cached item is removed.
SQL dependency
An item in the cache is dependent on changes in a table in a Microsoft SQL Server 2005, SQL Server 2000, or SQL Server 7.0 database. For SQL Server 2005, an item can be dependent on a row in a table. For more information, see Caching in ASP.NET with the SqlCacheDependency Class.
Aggregate dependency
An item in the cache is dependent on multiple elements through the use of the AggregateCacheDependency class. If any of the dependencies change, the item is removed from the cache.
Custom dependency
An item in the cache is configured with a dependency that you create in your own code. For example, you can create a custom Web service cache dependency that removes data from the cache when a call to a Web service results in a particular value.

Application cache Item Removal Notification:

You can be notified when an item is removed from the application cache. For example, if you have an item that takes considerable amount of processing time to create, you can be notified when it is removed from the cache so that you can replace it immediately. As a result, the next time the item is requested, the user does not have to wait for it to be processed. For more information, see How to: Notify an Application When an Item Is Removed from the Cache.

Add Item to Cache:

To add an item to the cache by directly setting the item via key and value

·         Add items to the cache as you would add items to a dictionary by specifying the item’s key and value.
The following code example adds an item named CacheItem1 to the Cache object:
Cache["CacheItem1"] = "Cached Item 1";

To add items to the cache by using the Insert method

·         Call the Insert method, passing the key and value of the item to add.
The following code example adds a string under the name CacheItem2:
Cache.Insert("CacheItem2", "Cached Item 2");

To add an item to the cache by specifying a dependency

·         Call the Insert method, passing it an instance of the CacheDependency object
The following code example adds an item named CacheItem3 that is dependent on another item in the cache named CacheItem2:
string[] dependencies = { "CacheItem2" };
Cache.Insert("CacheItem3", "Cached Item 3",
    new System.Web.Caching.CacheDependency(null, dependencies));
example shows an item named CacheItem4 added to the cache and having a file dependency set on the file named XMLFile.xml:
Cache.Insert("CacheItem4", "Cached Item 4",
    new System.Web.Caching.CacheDependency(
    Server.MapPath("XMLFile.xml")));
The following code example shows how to create multiple dependencies. It adds a key dependency on another item in the cache named CacheItem1 and a file dependency on the file named XMLFile.xml.
System.Web.Caching.CacheDependency dep1 = 
    new System.Web.Caching.CacheDependency(Server.MapPath("XMLFile.xml"));
string[] keyDependencies2 = { "CacheItem1" };
System.Web.Caching.CacheDependency dep2 = 
    new System.Web.Caching.CacheDependency(null, keyDependencies2);
System.Web.Caching.AggregateCacheDependency aggDep = 
    new System.Web.Caching.AggregateCacheDependency();
aggDep.Add(dep1);
aggDep.Add(dep2);
Cache.Insert("CacheItem5", "Cached Item 5", aggDep);
Caching in ASP.NET with SqlCacheDependency class:
 
SQL cache dependency is available for the page output cache as well as Application cache.

ASP.NET SQL cache dependency offers the following features:

·         You can use SQL cache dependency for both the application cache and the page output cache.
·         You can use SQL cache dependency with SQL Server 7.0 and later versions.
·         You can use SQL cache dependency in a Web garden (multiple processors on one server) or a Web farm (multiple servers running the same application).
·         The database operations associated with SQL cache dependency are simple and therefore do not incur a heavy processing cost on the server.
·         You do not need extensive SQL knowledge to configure SQL cache dependency in your application and in SQL Server. ASP.NET includes tools that automate the configuration. Additionally, you can use theSqlCacheDependencyAdmin class to programmatically configure SQL cache dependency.

Enable SQL Caching:

In order to use SQL cache dependency in SQL Server 7.0 and SQL Server 2000, you must configure SQL Server to support it. ASP.NET provides utilities to configure SQL caching on SQL Server, including a tool named Aspnet_regsql.exe and the SqlCacheDependencyAdmin class. For more information on enabling SQL cache dependency with SQL Server see How to: Cache Page Output with Cache Key Dependencies.

SQL Server 2005 implements a different model for cache dependency than SQL Server 7.0 and SQL Server 2000. You do not need to go through any special configuration steps to enable SQL cache dependency on SQL Server 2005. Additionally, SQL Server 2005 implements a change notification model where notifications are sent to subscribing application servers, rather than relying on the polling model required in earlier versions of SQL Server.

Once you have configured SQL Server 7.0 or SQL Server 2000 for cache dependencies, or have created the appropriate command dependency in SQL Server 2005, you can configure your application to use SQL cache dependency just as you would configure any other cache dependency. For example, you can create a cache profile in the Web.config file and then reference that cache profile on each page that should use the SQL cache dependency. You could also use SQL cache dependency by enabling it programmatically using the SqlCacheDependency class. For more information, see How to: Cache Page Output with Cache Key Dependencies.

To make cached page output dependent upon another cache item

1.       In a page, specify cache settings either declaratively or programmatically. For more information, see How to: Set Expiration Values for ASP.NET Page CachingSetting the Cacheability of a Page, and Caching Multiple Versions of a Page.
2.       In page code, call the AddCacheItemDependency method. As the cacheKey parameter, pass the name of the cache item on which to create a dependency.
The following code example shows how to set a dependency on the item named ProcessIntensiveReport. When this item is modified or removed, the page output will be removed from the cache.
protected void Page_Load(object sender, EventArgs e)
{
    Response.AddCacheItemDependency("ProcessIntensiveReport");

    // Set additional properties to enable caching.
    Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
    Response.Cache.SetCacheability(HttpCacheability.Public);
    Response.Cache.SetValidUntilExpires(true);
}
Note
You cannot call the AddCacheItemDependency method in an ASP.NET user control. However, in any user control that specifies the @ OutputCache directive, you can create a CacheDependency object that describes the cache key dependency and assign it to the Dependency property of the UserControl object.

How to make page cacheable:

To cause a page to be added to the output cache, you establish an expiration policy for that page. You can do this declaratively or programmatically.

To set output-cache expirations for a page declaratively

·         Include an @ OutputCache directive in the ASP.NET page (.aspx file) whose response you want to cache. Set the Duration attribute to a positive numeric value, and set the VaryByParam attribute to a value.
Note
The @ OutputCache directive sets the Cache-Control header to Any by default.
·         For example, the following @ OutputCache directive sets the page’s expiration to 60 seconds:
·         <%@ OutputCache Duration="60" VaryByParam="None" %>
Note
You must include a VaryByParam attribute when using the @ OutputCache directive or a parser error will occur. If you do not want to use the functionality offered by the VaryByParam attribute, set its value to “None”. For more information, see Caching Multiple Versions of a Page.

To set output-cache expirations for a page programmatically

·         In the page’s code, set the expiration policy for the page on the Cache property of the Response object.
Note
If you set expirations for a page programmatically, you must set the Cache-Control header for the cached page as well. To do so, call the SetCacheability method and pass it the HttpCacheabilityenumeration value Public.
·         The following code example sets the same cache policy as the @ OutputCache directive does in the preceding procedure.
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetValidUntilExpires(true);
When the cached page expires, the subsequent request for the page causes a dynamically generated response. This response page is cached for the specified duration.

For ASP.NET pages, you can set cacheability by using values in the HttpCacheability enumeration. The enumeration has the following values. The first three map directly to Cache-Control HTTP header settings, and the last three are special values.

·         NoCache   Specifies that the device making the request should get the response from the Web server each time.
·         Public   Allows the response to be cached by clients and shared (proxy) caches.
·         Private   Specifies that the response is cacheable only on the client and not by shared (proxy server) caches.
·         Server   Specifies that the response is cached only at the origin server.
·         ServerAndNoCache   Applies the settings of both Server and NoCache to indicate that the content is cached at the server but all others are explicitly denied the ability to cache the response.
·         ServerAndPrivate   Specifies that a response should be cached only on the origin server and on the requesting client; proxy servers are not allowed to cache the response.

You can set a page’s cacheability declaratively by including a Location attribute in the @ OutputCache directive and specifying one of the OutputCacheLocation enumeration values. You can also set a page’s cacheability programmatically using the SetCacheability method to specify an HttpCacheability value for the page. The method is accessible through the Cache property of the Response class.

Page Output Cache Configuration:

You can configure page output caching in these places:

·         Configuration files   You can configure page output cache settings in any configuration file in the application configuration hierarchy, including the Machine.config file (to make settings for all Web applications on the computer) and your application-specific Web.config file (to make settings for a single application).
·         Individual pages   You can set caching options in individual pages either declaratively or programmatically. You can also apply cache profiles created in the configuration file to individual pages.
·         User controls   You can set caching in individual user controls either declaratively or programmatically. This is an easy way to cache content within a page that is otherwise not cached.

Web.config Cache Configuration Settings

There are two top-level configuration sections for the page output cache in the Web.config file: the OutputCacheSection and the OutputCacheSettingsSection.

The OutputCacheSection section is used to configure application-scope settings, such as whether page output caching is enabled or disabled. For example, you can disable page output caching for the entire application by adding enableOutputCache="false" to the OutputCacheSection in your Web.config file. Settings in the configuration file take precedence over cache settings in individual pages, so the example setting means that output cache will not be used.

The OutputCacheSettingsSection is used to configure profiles and dependencies that can be used by individual pages. For example, the following code creates an OutputCacheProfile named CacheProfile1 that will cache the implementing page for 60 seconds:

  
    
  

Machine.config Cache Configuration Settings

The configuration sections for the Machine.config file are the same as for the Web.config file, except that you can lock configuration settings in the Machine.config file so that they cannot be overridden by individual applications at any level. This might be necessary in a shared hosting scenario in which the hoster does not want individual applications modifying the cache configuration. For more information see How to: Lock ASP.NET Configuration Settings.

Page Cache Configuration Settings

You can configure caching in individual pages by applying cache profiles that have been defined in a configuration file. Alternatively, you can configure individual cache properties in the @ OutputCache directive or by setting attributes in the page’s class definition. For more information see @ OutputCache and Setting the Cacheability of a Page.

User Control Cache Configuration Settings

You can configure user control caching by setting the @ OutputCache directive in the user control file or by setting the PartialCachingAttribute attribute in the control’s class definition. For more information, seeCaching Portions of an ASP.NET Page.

Caching the Page and User Control in different duration:

For example, if page output caching is set to 100 seconds and the user control output caching is set to 50 seconds, the entire page, including the user control, is stored in the output cache for 100 seconds, regardless of the shorter setting for the user control.

For example, if page output caching is set to 50 seconds and the user control’s output caching is set to 100 seconds, the user control expires once for every two times the rest of the page expires.

How to implement caching

1.       User Control:
<%@ OutputCache Duration="120" VaryByParam="None" %>
OR
[PartialCaching(120)]
public partial class CachedControl : System.Web.UI.UserControl
{
    // Class Code
}

2.  Page:
 
<%@ OutputCache Duration="60" VaryByParam="None" %>

OR
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetValidUntilExpires(true);

Notify Application when an item is removed from Cache:
 (Magic of ReportRemovedCallback delegate)

Example:

using System;
using System.Web;
using System.Web.Caching;
public static class ReportManager
{
    private static bool _reportRemovedFromCache = false;
    static ReportManager()
    { }

    public static String GetReport()
    {
        lock (typeof(ReportManager))
        {
            if (HttpContext.Current.Cache["MyReport"] != null)
                return (string)HttpRuntime.Cache["MyReport"];
            else
            {
                CacheReport();
                return (string)HttpRuntime.Cache["MyReport"];
            }
        }
    }

    public static void CacheReport()
    {
        lock (typeof(ReportManager))
        {
            HttpContext.Current.Cache.Add("MyReport",
                CreateReport(), null, DateTime.MaxValue,
                new TimeSpan(0, 1, 0), 
                System.Web.Caching.CacheItemPriority.Default,
                ReportRemovedCallback);
        }
    }

    private static string CreateReport()
    {
        System.Text.StringBuilder myReport = 
            new System.Text.StringBuilder();
        myReport.Append("Sales Report
");
        myReport.Append("2005 Q2 Figures
");
        myReport.Append("Sales NE Region - $2 million
");
        myReport.Append("Sales NW Region - $4.5 million
");
        myReport.Append("Report Generated: " + DateTime.Now.ToString() 
            + "
");
        myReport.Append("Report Removed From Cache: " + 
            _reportRemovedFromCache.ToString());
        return myReport.ToString();
    }

    public static void ReportRemovedCallback(String key, object value, 
        CacheItemRemovedReason removedReason)
    {
        _reportRemovedFromCache = true;
        CacheReport();
    }
}

Be Connected...
Satyendra
,

About Satyendra Mishra

Satyendra is a Technical Project Manager with 12+ years of experience on Project Management, Microsoft Technologies including ASP.NET, ASP.NET MVC, C#, SharePoint (On premises & Office 365), JavaScript Framework (AngularJS) and related technologies. He is a person with belief, sky is limit for a hard working and dedicated individual. That’s why he devoted himself to field of Software Development and now both are growing with each other. Every year for him turned out to be best year and he received enormous support and love from his companies and his clients from around the world. Now with vast knowledge of software development and its outsourcing process, he decided to move himself into knowledge sharing. Keep a fact in your mind about the comfort level of your clients and this will make you king/queen of your area.
View all posts by Satyendra Mishra →

Leave a Reply

Your email address will not be published. Required fields are marked *