Showing posts with label SQL Caching. Show all posts
Showing posts with label SQL Caching. Show all posts

Wednesday, 2 November 2011

Caching in Asp .Net



Caching In ASP.NET 

One of the performance issues of a database drive Web application is retrieving data from a database. If it needs to access the database with every page request, then the response will be very slow. We can avoid this situation with cache technique. You can cache the data in memory when the page is requested for the first time, and hence forth for the subsequent request the page can be served from cache. This reduces network trips to the backend, minimize server workload and database load too, hence the performance increase.

Even though, ASP.NET 1.0 offered variety of caching, if the cache content of a table in memory is changed in the database after the first request, will that change get reflect in your page when it is served from the cache? No, your application will display old data only. Unfortunately we don’t have a sufficient solution for this problem prior to the release of ASP.NET 2.0. The newer version is having a new feature called “SQL Cache Invalidation”, an opt solution for this problem. Further the new framework extends the existing caching techniques more powerful and easier to use and manage.

In this article we are going to see the new and improved caching techniques available in APS.NET2.0. First, let us see about Data Caching enhancements.

Data Caching
Data Caching allows you to cache random objects, so that your applications need not to recreate them from the server. A new class System.Web.Caching.CacheDependency available in ASP.NET 2.0 enables you to write your own implementation of cache dependency. Further you can cache the data using the new DataSource controls available in ASP.NET 2.0, the following code describes how to enable a cache with a SqlDataSource control.
 
<asp:SqlDataSource
ID="SqlDataSource1"
EnableCaching="true"
CacheDuration="600"
ConnectionString="Server=localhost;database=Pubs"
SelectCommand="SELECT Title FROM Authors"
Runat="server" />
SQL Cache Invalidation
As we have seen earlier, your application may give old data when it is served from cache, without the awareness about the data change made in the database. In ASP.NET 1.X we used to give minimum value for Cache Duration. But this will increase the network load. If we give maximum value for Cache Duration then we will get wrong data. Instead of this if there a notification system, which will notify when ever the data is getting changed in the database, will it solve this problem…? Yes, that is SQL Cache Invalidation. It allows you to update your cached content automatically whenever the data changes in the database.

We can split this feature into two cases, based on the SQL Server version you are having. The new version of SQL Server series ‘Yukon’ codename for SQL Server 2005 can be configured to notify your web application whenever changes have been made to database or a database table or a database row. But in SQL Server 7/ SQL Server 2000, there is no built in notification model. Hence, ASP.NET application has to constantly monitor the database to check for changes. The following figures describe these two cases.

In either case, if there is some change, then items added to the cache that depend on the database are removed from the cache. That is, those items are invalidated.

How to enable SQL Cache Invalidation
You have to do some setup process before start using SQL Cache Invalidation. Two steps involved in this setup process.
1.    Configure SQL Server to support SQL Cache Invalidation
2. Add configuration information into your application’s web.config file
1. Configuring SQL Server
To configure your SQL Server you have to use the command line utility which is, available in your \WINDOWS\Microsoft.NET\Framework\v2.x.xxxxx. Execute the tool with the following options from command prompt.
aspnet_regsql –E –d Pubs –ed

The above line will enable the pubs database for SQL Cache Invalidation.
The following line will enable the Authors table for the same.

Aspnet_regsql –E –d Pubs –t Authors –et

What is happening behind the scenes…?
When you run the first command it will add a new database table called ‘AspNet_SqlCacheTablesForChangeNotification’. This table will have a list of all tables, which are enabled for SQL Cache Invalidation.



When you run the second command, a new trigger will be added to your database and it’ll fires whenever there is a modification in the table you mentioned, in our case ‘Authors’, and it updates the new table created in the previous step.

2. Configuring your web.config file
Include the following lines of code under <system.web> tag in your web.config file.
 
<caching>
<sqlCacheDependency enabled ="true" pollTime="60000">
<databases>
<add name="pubs" connectionStringName="AppConnectionString1" />
</databases>
</sqlCacheDependency>
</caching>
In the above code PollTime value is in milliseconds. In our case 60000 milliseconds means once a minute, application will check the cache table for changes.

The following example code will displays the contents of Titles table in the Pubs database with the advantage of SQL Cache dependency on the sqldatasource control. The page will monitor the table for changes. As along as there is no changes, the page will be served from the cache, once the data get changed the response is invalidated and the data source control reloads the data.
 
<asp:SqlDataSource ID="SqlDataSource1" Runat="server" CacheDuration="500" SqlCacheDependency="PubsDB: Titles" ProviderName="<%$ ConnectionStrings:AppConnectionString1.ProviderName %>"> </asp:SqlDataSource>
If you want to do the same SqlCacheDependency with <%@ OutputCache %> then you have to change your code as shown below.
 
<%@ OutputCache Duration="3600" VaryByParam="none" sqlDependency="pubs:Titles"%>
<asp:SqlDataSource ID="SqlDataSource1" Runat="server" ProviderName="<%$ ConnectionStrings:AppConnectionString1.ProviderName %>"> </asp:SqlDataSource>
Output Caching

Output Caching allows you to cache dynamic page and user control responses on any Http 1.1 cache-capable device in the output stream. Now we are going to see about some of the new enhancements in this technique.

Post Cache Substitution

Let us consider the following scenario, one of your application page is having a small dynamic region as time. In this case you can’t cache the entire page, since you need to update your page time with current time. So you are forced to use a separate usercontrol with the help of fragment caching. Instead of this ASP.NET 2.0 introduced a new feature called post cache substitution (a new API Response.Write Substitution), using this you can insert the dynamic contents, time in you case, into the particular page in every request.

Disk Output Cache

All your cached contents are stored in memory, if it is removed from the output cache due to memory constraint what can you do….? Here comes the new feature, you can save cached response to disk also, in addition to storing them in memory. So, incase of memory constraint, it happened to remove the cached content from memory, still you are having in them in disk. The cool thing is, it persist across application restarts, so that when the application comes back, the page can be served from your disk cache. You have to include
DiskCacheable="true" %> in <%@ OutputCache %> Directive
to turn on this feature for your page.

Cache Profiles

A page can be cached and served based on the cache profile settings in your configuration file. This allows you to manage no. of pages centrally. Still, you can override the cache profile settings with the page cache settings using output cache directive. The following code snippet shows the cache profile setting in the configuration file and corresponding usage of that profile in the page output directive.
Configuration file setting…
<caching >
<outputCacheSettings>
<outputCacheProfiles>
<add name="For1Minute" duration="60" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
Page setting…

<%@ OutputCache CacheProfile="CacheFor60Seconds" VaryByParam="Id" %>
Fragment Caching
In ASP.NET 1.0 you can specify the cache setting for fragment cache during design time only. But in ASP.NET 2.0 the fragment caching ControlCachePolicy API allows you to control caching settings for fragment caching of user control, programmatically.

Conclusion

Already you have tasted the benefits of caching, with ASP.NET 1.x. Now, the new DataSource controls allows you to cache the data, without writing code, SQL Cache Invalidation allows you to keep always updated cache content, seamless to the user, post cache substitution allows you to insert the dynamic content into a cached page. Totally the newer version of ASP.NET brings some more new enhancements in caching, which makes caching easy and more effective.