ASP.NET, Coding

Understanding ASP.NET Caching Options

To improve application speed and reduce the response times, Asp.Net enables us to use two types of caching : Output and Data caching. I am going to show how to implement these two types of caching in the following.

There are basically two types of caching in Asp.Net. The output caching stores a copy of the final rendered html page that is sent to the client. And the data caching stores important pieces of information that are time-consuming to reconstruct in the memory of the server globally.

There are two types of output caching : Page-level output caching and Fragment(UserControl)-level output caching

First I will show how to implement Page-level output caching. To demonstrate output caching, lets start by creating a web application in visual studio.net 2005 by clicking File > New > Web Site, select Asp.Net Web Site from the opening dialog box and name the project and then click ok.

Understanding ASP.NET Caching Options 01

Open up the default.aspx file and drag and drop a label on it.

Open up the default.aspx.cs file and type the code below in the Page_Load event handler as follows :

protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text = DateTime.Now.ToString();
    }
Click ctrl + f5 and run the application. 

Each time you refresh the page you will see the current date time of the server in this format : 22.04.2008 06:20:58 – 22.04.2008 06:20:59 – 22.04.2008 06:21:00
Now Open up the default.aspx page in the html view and add output caching directive right after the page directive as follows:

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

Now when you run the application again, it will display the current time once and keep displaying the same time during 5 seconds and will refresh the time with the current time value when that 5 seconds expire. The VaryByParam and Duration attributes are both required attributes and your code wont compile if you forget to use any of them. If your Page generates different outputs in accordance to the requesting query string, then you can use the varybyparam attribute to make the asp.net cache different versions of the rendered html based on the query string parameter values. Let’s say i request the Page like this mysite/default.aspx?page=one and then like this mysite/default.aspx?page=two.If you set the VaryByParam attribute to “page”, For both these requests, Asp.Net caches different versions of the final page output(rendered html),and when requested with those parametres,it serves from the cache accordingly.

There are times that you dont want to cache a copy of the whole page but want a part of it instead. For these cases Fragment Caching takes place.
Now add a user control to the project you just created by right clicking the project icon in the solution explorer and choosing Add New Item from the menu.

Understanding ASP.NET Caching Options 02

Select WebUserControl and click Add. Now Cut and Paste the output cache directive from the Default.aspx page to the WebUserControl.ascx, drag and drop a label on it and add the same Page_Load event handler to the WebUserControl.ascx.cs file
protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text = DateTime.Now.ToString();
    }

Ok Now drag and drop the user control to the default.aspx page and rerun the application. In this case although the label in the default.aspx page refreshes it self the label in the webusercontrol.ascx wont until 5 seconds expire.

To demonstrate the data caching we will create a very basic table in the sql server 2005 or sql server 2005 express edition. Create a table and name it names and create the columns as follows.

Understanding ASP.NET Caching Options 03

Open up the default.aspx.cs page and add the System.Data.SqlClient namespace
Open up the default.aspx page and drag and drop a gridview control.
Now create the ConnectionString and SqlDataAdapter in the page load event handler as follows:

if (Cache["myItem"] == null)
        {
//modify the connection string according to your environment.
            SqlConnection con = new SqlConnection("Data Source=SERKANMYSQLSERVER2005;Initial Catalog=deneme;Integrated Security=True;Pooling=False");
            SqlCommand com = new SqlCommand("select * from names", con);
            SqlDataAdapter da = new SqlDataAdapter(com);
            DataTable dt = new DataTable();
            da.Fill(dt);
            GridView1.DataSource = dt;
            GridView1.DataBind();
            Cache.Insert("myItem", dt);
        }
        else
        {
            GridView1.DataSource = Cache["myItem"] as DataTable;
            GridView1.DataBind();
        }

Here what i do is simple. In the Page load event i check if there is a cached item with the “myItem” keyword, if there is not then i make a connection to the database and query the results to fill my gridview and insert the result set to the cache as well. Then after the first request to this page since the Cache[“myItem”] is not null it enters in the else statement and returns the results from the cache object. You can test it by starting the application in the debug mode and set a break point in the page load event. Just refresh the page and you will see after the first request it brings the results from the Page’s Cache object.
In this article we have seen two different caching options in Asp.Net : Output and Data Caching.

The article is submitted as a word document, and the Sample application is also added as a .zip file. The sample application would now work unless you create a database in your local computer because i didnt created the database in the App_Data folder. I used a registered Sql Server 2005 database instead.