Wednesday, October 22, 2008

Caching Data for Better Performance

Caching Data for Better Performance
Using cache to improve website access time

Introduction

A cache is a temporary storage area where frequently accessed data can be stored for rapid access. Once the data is stored in the cache, future use can be made by accessing the cached copy rather than re-retrieve the original data, so that the average access time is shorter. Caching probably is one of the least used features of ASP.NET. Most developers do not get into the details of caching at until some level, and some never use it at all.

Main

Caching can be achieved in ASP.NET pages by the following ways:

1. Specifiying the @OutputCache directive at the top of a webpage as introduced in ASP.NET 1.1 and using class First, using @OutputCache directive. You can include this directive at the top of the aspx page which you want to cache and then set the Location of the Cache. Example:


<%@ OutputCache Duration="60" VaryByParam="None" %>

Client Cache:

<%@ OutputCache Duration="60" Location="Client" %>

Proxy Server Cache:

<%@ OutputCache Duration="60" Location="Downstream" %>

Server Cache:

<%@ OutputCache Duration="60" Location="Server" %>

Similar to the above is by using the cache System.Web.Caching.Cache class. You can do it by write Cache.Insert("key", data), and you retrieve it by writing data = Cache["key"]. Example:

private void Button1_Click(object sender, System.EventArgs e)

{
if (Cache["Key"] == null) {data = Cache["Key"] }
}

There is a few weakness of this caching system. When the expiration time or cache reached, the data is removed from the cache and you have to read it again from the database even if it hasn't actually changed in the database. And also, if you cache the data for 30 minutes, and the data constantly changed, you'll be displaying not updated data for almost 30 minutes.

2. Second method by integrate with ASP.NET with SQL server to create a cache dependency support. Now, The Cache class has been enhanced for ASP.NET 2.0. It now supports dependencies to database tables. You can cache the data for an indeterminate period, until the data in the source database's table actually changes.

The step to integrate ASP.NET cache with SQL Server Express 2005 as follow:

aspnet_regsql.exe -E -S .\SqlExpress -d aspnetdb -ed

The -E option specifies that you're using Windows integrated security and thus don't need to pass username and password. The -S option specifies the SQL Server instance name. SqlExpress is the default instance name you get when you install SQL Server 2005 Express. The -d option specifies the database name aspnetdb, and the -ed is use for enable database.

The next step is to add support for a specific table, which means you must create a record in the AspNet_CacheTablesForChangeNotification table, and a trigger for the table to which you're adding support:

aspnet_regsql.exe -E -S .\SqlExpress -d aspnetdb -t Customers –et

-t parameter specifies the table name, and the -et is use for enable table. For this commands to work, the aspnetdb database must be already attached to a SQL Server instance. We can use the sqlcmd.exe command-line program, run from the VS 2005's command prompt. Everyone should have this program. It is started from a Visual Studio command prompt as follows:

  public List<CUSTOMERDETAILS> GetCustomers()

{
List<CUSTOMERDETAILS> customers = null;
if (Cache["Customers"] != null)
{
customers = (List<CUSTOMERDETAILS>)Cache["Customers"];
}
else
{
using (SqlConnection cn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", cn);
customers = FillCustomerListFromReader(cmd.ExecuteReader());
SqlCacheDependency dep = new SqlCacheDependency(
"aspnetdb-cache", "Customers");
Cache.Insert("Customers", customers, dep);
}
}
return customers;
}


sqlcmd -E -S .\SqlExpress


Once you are in the sqlcmd program, you run the following command to attach your database:


sp_attach_db "aspnetdb", "D:\Workdir\Web\caching\App_Data\aspnetdb.mdf"

go


Then run the two aspnet_regsql commands listed above and then detach the database as follows:

sp_detach_db "aspnetdb"

go


The last thing to do to complete the SQL dependency configuration is to write the polling settings in the web.config file:

<CONFIGURATION>

<CONNECTIONSTRINGS>
<ADD name="aspnetdb" connectionString="" />
CONNECTIONSTRINGS>
<SYSTEM.WEB>
<CACHING>
<SQLCACHEDEPENDENCY enabled="true" pollTime="10000">
<DATABASES>
<ADD name="aspnetdb-cache" pollTime="2000" connectionStringName="aspnetdb" />
DATABASES>
SQLCACHEDEPENDENCY>
CACHING>
SYSTEM.WEB>
CONFIGURATION>

As you see, there is an entry named aspnetdb-cache that refers to the databases by using the connection string called aspnetdb and that defines a polling interval of 2 seconds.

After everything is configured, you can finally write the code to actually cache the data. To create a dependency to a Customers table, you create an instance of the System.Web.Caching.SqlCache Dependency class. Example:

SqlCacheDependency dep = new SqlCacheDependency("aspnetdb-cache", "Customers");

Cache.Insert("Customers", customers, dep);


Example that you have a GetCustomers method in your config.cs or other data access layer class that returns a list of CustomerDetails objects filled with data from the Customers table. You could implement caching as follows:


The method first checks whether the data is already in cache. If it is, then it retrieves the data from there, otherwise, it first retrieves it from the database, and then caches it for later use.

Conclusion

Caching has proven to be extremely effective in many large scale websites. Choosing the right Caching strategy is very important for your web and server performance.

References

All the useful links or references that can help users learn about your tutorial

  1. ASP.NET caching overview
  2. How to cache in ASP.NET by using visual C# .NET

No comments: