Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger


Monday, September 29, 2008

Caching in ASP.NET (Part I)

The ability to store data in the main memory and then allow for retrieval of the same as and when they are requested is one of the major factors that can yield high performance and scalable applications. This results in a gain in the application’s overall throughput by serving the subsequent requests for data from the Cache rather than recreating them or retrieving them from the database or any other storage device that works much slower compared to the main memory. This is one of the most striking features in Microsoft’s ASP.NET compared to its earlier counterparts and has been enhanced further with the introduction of the new release of ASP.NET (ASP.NET 2.0). This is the first in the series of articles on Caching in ASP.NET and discusses Caching, its types, benefits and the new features of Caching in ASP.NET 2.0.

Caching types, Cache Dependencies and Cache Expirations

ASP.NET features several different types of caching namely Page Output Caching, Page Fragment Caching and Data Caching. In Page Output Caching, the entire page is cached in memory so all the subsequent requests for the same page are addressed from the cache itself. In Page Fragment Caching, a specific a portion of the page is cached and not the entire page. Page Output or Fragment Caching can be enabled or disabled at the Page, Application or even the Machine levels.
Data Caching allows us to cache frequently used data and then retrieve the same data from the cache as and when it is needed. We can also set dependencies so that the data in the cache gets refreshed whenever there is a change in the external data store. The external data store can be a file or even a database. Accordingly, there are two types to dependencies, namely, file based and Sql Server based. There are also differing cache expiration policies.

New Caching features in ASP.NET 2.0

ASP.NET 2.0 has introduced a lot of new features in Caching. This new version of ASP.NET includes an excellent feature called automatic database server cache invalidation which is in turn based on database triggered cache invalidation technique. This powerful and easy-to-use feature enables us to output cache database-driven page and partial page content within a site and then leave it to ASP.NET invalidate these cache entries automatically and refresh the content whenever the there are any changes in the database. This ensures that the data in the Cache is in sync with that of the database. Note that the Cache API in ASP.NET 1.x does not allow you to invalidate an item in the cache when the data in the database changes. It is possible to invalidate cached data based on pre-defined conditions that relate to any change in the data in an external data store on which the dependency has been set. The data gets deleted from the Cache with any change in the data in the external data storage. However, the cached data cannot be refreshed directly.

ASP.NET 2.0 also features numerous enhancements to the Cache API. The CacheDependency class of ASP.NET 1.x was sealed to prevent further inheritance. Thus preventing extension of this class to provide custom cache dependency features. ASP.NET 2.0 Cache API provides the ability to create custom cache dependency classes that are inherited from the CacheDependency class. I would discuss all these issues in details in the subsequent articles in this series of articles on Caching in ASP.NET applications.

Page Caching in ASP.NET

There are two types of Page caching, namely, Page Output Caching and Page Fragment Caching. Page Fragment Caching is also known Partial Page Caching.

Page Output Caching

According to MSDN, Page Output Caching is "the simplest form of caching, output caching simply keeps a copy of the HTML that was sent in response to a request in memory. Subsequent requests are then sent the cached output until the cache expires, resulting in potentially very large performance gains (depending on how much effort was required to create the original page output—sending cached output is always very fast and fairly constant)".

The ASP.NET Cache Engine is responsible for providing support for Caching in ASP.NET. But, how does it work? The output of the ASP.NET web pages is cached such that all subsequent requests for the same page are served from the cache instead of any other persistent storage medium. When we say that the output of a web page is cached, we imply that the web page output is stored in the cache memory. Whenever a new page request is made, the ASP.NET Cache Engine is activated. It checks whether there is a corresponding cache entry for this page. If one is found, it is known as a Cache hit, else, we say that a cache miss has occurred. If there is a cache hit, i.e., if the ASP.NET Cache engine finds a corresponding cache entry for this page, the page is rendered from the cache, otherwise, the page being requested is rendered dynamically. Page Output caching can be specified in either of the following two ways:

Declarative Approach
Programmatic Approach

Declarative Approach

The declarative specification here implies that Page Output Caching is specified at the design time by adding the OutputCache directive in the web page source.

The following is the complete syntax of page output caching directive in ASP.NET.

<%@ OutputCache Duration="no of seconds"
Location="Any | Client | Downstream | Server | None"
VaryByControl="control"
VaryByCustom="browser |customstring"
VaryByHeader="headers"
VaryByParam="parameter" %>

We can specify output caching in an aspx page at design time using the OutputCache directive as shown below.

<%@OutputCache Duration="25" VaryByParam="none" %>

The VaryByHeader and VaryByCustom parameters of the OutputCache directive are used to enable customization of the page's look or content based on the client that is accessing them. The cache duration is a mandatory parameter and specifies how long (in seconds) the web page remains in the cache memory. The VaryByParam parameter is optional and is used to cache different views of the page, i.e., whether the cached page would have different versions based on a specific parameter. A value of * in the same parameter indicates that the page would be cached based on all the Get/Post parameters. We can also specify one or more Get/Post parameter(s). The VaryByParam parameter is particularly useful in situations where we require caching a page based on some pre-defined criteria. As an example, we might require to cache a specific page based on the PatientID. The OutputCache directive needs to be specified as shown below.

<%@OutputCache Duration="10" VaryByParam="PatientID" %>

The VaryByParam parameter can also have multiple parameters as shown in the example below.

<%@OutputCache Duration="20" VaryByParam="PatientID;ProviderID" %>

The location parameter in the OutputCache directive is used to specify the cache location, i.e., from where the client received the cached page. This should be one of the possible four OutputCacheLocation enumeration values, namely, Any, Client, Downstream, None, Server. An example is given below.

<%@OutputCache Duration="10" VaryByParam="*" Location = "Any"%>

Programmatic Approach

Page Output Caching can also be specified programmatically using the Response.Cache.SetCacheability method. The parameters to this method can be “NoCache”, “Private”, “Public” or “Server”. Refer to the code example below that illustrates how to set a page’s cache ability programmatically:

Response.Cache.SetCacheability (HttpCacheability.Server);

It is also possible to set the OutputCache on all the pages in an ASP.NET application programmatically in the Global.asax page. Refer to the code snippet that follows:--

void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Server);
}

The source code given in the above code snippet sets the cache ability programmatically in the BeginRequest event of the application's global class.

Page Fragment Caching

Also known as Partial Page Caching, this is a feature that allows specific portions of the web page to be cached rather than caching the entire web page and is useful in situations where a particular web page can contain both static and dynamic content. MSDN says, “Often, caching an entire page is not feasible, because certain parts of the page are customized for the user. However, there may be other parts of the page that are common to the entire application. These are perfect candidates for caching, using fragment caching and user controls“. The term “fragment” implies one or more user controls in the web page. Note that each of these user controls can have different cache durations. The following statement depicts how this can be accomplished.

<%@ OutputCache Duration="10"
VaryByControl="PatientID” VaryByParam="*"%>


New Page Caching Features in ASP.NET 2.0

With ASP.NET 2.0, you do no longer need to split your pages into multiple .ascx user control files for implementing Page Fragment Caching or Partial Page Caching. You are free to do the same using Output Cache Substitution – a concept that provides you the facility to cache the output of a web page with some dynamic portions inside in page. Note that this is in sharp contrast to ASP.NET 1.x when we needed to implement the same as, in the partial page caching; “the overall page is dynamic, with cached regions in the middle”.

The following code snippet illustrates how we can implement output cache substitution using the control.

Implement the method myMethod in such a way that it contains some code that would display static data. Now, the entire page would be cached except the contents of the control. Note that you can also achieve this programmatically using the Response.WriteSubstitution method.

Conclusion

Caching is a great tool that can be used to boost the performance web applications. This article has discussed the ways of storing data in the cache using ASP.NET with code examples wherever applicable. The next part in this series discusses storing data in the cache, i.e., Data Caching in ASP.NET.

No comments:

Post a Comment

Recent Posts

Archives