Cache in ASP.NET by using Visual C# .NET

ASP.NET provides easier methods to control caching. You can use the @ OutputCache directive to control page output caching in ASP.NET. Use the HttpCachePolicy class to store arbitrary objects, such as datasets, to server memory. You can store the cache in applications such as the client browser, the proxy server, and Microsoft Internet Information Services (IIS). By using the Cache-Control HTTP Header, you can control caching.
Cache ASP.NET pages
Use the @ OutputCache directive to cache, or you can cache programmatically through code by using Visual Basic .NET or Visual C# .NET. The @ OutputCache directive contains a Location attribute. This attribute determines the location for cached item. You can specify the following locations:

  1. Any – This stores the output cache in the client’s browser, on the proxy server that participates in the request, or on the server where the request is processed. By default, Any is selected.
  2. Client – This stores output cache in the client’s browser.
  3. Downstream – This stores the output cache in any cache-capable devices that participate in the request.
  4. Server – This stores the output cache on the Web server.
  5. None – This turns off the output cache.

The following are code samples for the @ OutputCache directive and equivalent programmatic code.

1.To store the output cache for a specified duration

Declarative Approach:
<%@ OutputCache Duration=”60″ VaryByParam=”None” %>

Programmatic Approach:
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);

2.To store the output cache on the browser client where the request originated

Declarative Approach:
<%@ OutputCache Duration=”60″ Location=”Client” VaryByParam=”None” %>

Programmatic Approach:
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Private);

3.To store the output cache on any HTTP 1.1 cache-capable devices including the proxy servers and the client that made request

Declarative Approach:
<%@ OutputCache Duration=”60″ Location=”Downstream” VaryByParam=”None” %>

Programmatic Approach:
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetNoServerCaching();

4.To store the output cache on the Web server

Declarative Approach:
<%@ OutputCache Duration=”60″ Location=”Server” VaryByParam=”None” %>

Programmatic Approach:
TimeSpan _timespan = new TimeSpan(0,0,0,60);
DateTime now = DateTime.Now;
Response.Cache.SetExpires(now.Add(_timespan));
Response.Cache.SetMaxAge(_timespan);
Response.Cache.SetCacheability(HttpCacheability.Server);
Response.Cache.SetValidUntilExpires(true);

5.To cache the output for each HTTP request that arrives with a different EmpID:

Declarative Approach:
<%@ OutputCache duration=”60″ varybyparam=”EmpID” %>

Programmatic Approach:
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.VaryByParams[“EmpID”] = true;
For the VaryByCustom attribute, the VaryByHeader attribute, and the VaryByParam attribute in the @ OutputCache directive, the HttpCachePolicy class provides the VaryByHeaders property and the VaryByParams property, and the SetVaryByCustom method.

Turn off client and proxy caching
To turn off the output cache for an ASP.NET Web page at the client location and at the proxy location, set the Location attribute value to none, and then set the VaryByParam value to none in the @ OutputCache directive. Use the following code samples to turn off client and proxy caching.

Declarative Approach:
<%@ OutputCache Location=”None” VaryByParam=”None” %>

Programmatic Approach:
Response.Cache.SetCacheability(HttpCacheability.NoCache);

Cache arbitrary objects in server memory
ASP.NET includes a powerful, easy-to-use caching mechanism that you can use to store objects that require a lot of server resources to create in memory. The Cache class implements this method. Instances are private to each application and the lifetime is tied to the corresponding application. To cache the arbitrary objects in ASP.Net by using the Cache class:

<%@ Import Namespace=”System.Data” %>
<%@ Import Namespace=”System.Data.SqlClient” %>

<html>

<script language=”C#” runat=”server”>

void Page_Load(Object Src, EventArgs E) {

DataView Source;

// Retrieve the DataView object from Cache. If not exist, then add DataView object to the Cache.

Source = (DataView)Cache[“MyDataSet”];

if (Source == null) {

SqlConnection myConnection = new SqlConnection(“Server=ServerName; database=MyDB; user id=UID; password=PWD;”);
SqlDataAdapter myCommand = new SqlDataAdapter(“select * from Employee”, myConnection);

DataSet ds = new DataSet();
myCommand.Fill(ds, “Employee”);

Source = new DataView(ds.Tables[“Employee”]);
Cache[“MyDataSet”] = Source;

MsgCache.Text = “Dataset created explicitly”;
}
else {
MsgCache.Text = “Dataset retrieved from cache”;
}

// Binding the DataView object with DataGrid.

TestDataGrid.DataSource=Source;
TestDataGrid.DataBind();
}

</script>

<body>

<form method=”GET” runat=”server”>

<h3><font face=”Arial”>Caching Data</font></h3>

<ASP:DataGrid id=”TestDataGrid” runat=”server”
Width=”700″
BackColor=”#ccccff”
BorderColor=”blue”
ShowFooter=”false”
CellPadding=3
CellSpacing=”0″
Font-Name=”arial”
Font-Size=”8pt”
HeaderStyle-BackColor=”#aaaad” />

<p>

<i><asp:label id=”MsgCache” runat=”server”/></i>

</form>
</body>
</html>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: