Caching in asp.net


Definition
Caching is the concept of storing frequently used data in the cache memory. It is mainly useful when we have to fetch same data again and again.

Advantages:
• It will increase the performance of website
• It will avoid the server overloading problem.

There are 3 type of Caching in asp.net

A. Output Caching
B. Fragment Caching
C. Data Caching

Output Caching

This is the simplest type of caching. It will cache the final rendered HTML page that is send to the client. When the same page is requested again, the control objects are not created, the page life cycle will not start and none of code will execute. So it will increase the performance of website.
Syntax for using Output Caching:
Wrire this syntax in page directive
<%@ OutputCache Duration=”20″ VaryByParam=”None” %>
Here page will cache upto 20 Seconds after that page will expire.

Caching at Client side:

In this case browser will store the page and it will reuse when somebody is requesting same page .
Syntax for Client caching:
<%@ OutputCache Duration=”20″ VaryByParam=”None” Location=”Client” %>

Caching and the Query String
For example if we have used Output caching and there is requirement to display dynamic page on basis of Query string then the above syntax will not give the correct output. It will cache the same page every time. So we have to write the syntax like this
<%@ OutputCache Duration=”20″ VaryByParam=”*” %>

Caching with Specific Parameters

For example if we have used Output caching and there is requirement to display dynamic page on basis of some parameter or some dropdown field or some textbox field then the above syntax will not give the correct output. It will cache the same page every time. So we have to write the syntax like this
<%@ OutputCache Duration=”20″ VaryByParam=”txtName” %>
Here txtName is the parameter. It will cache the page on basis of txtName

Here is one sample example

Step1: Implement the caching syntax in aspx page like this

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”OutPutCaching.aspx.cs” Inherits=”OutPutCaching” %>

<%@ OutputCache Duration=”20″ VaryByParam=”txtName” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;

<head runat=”server”>

<title></title>

</head>

<body>

<form id=”form1″ runat=”server”>

<div style=”margin-left:200px”>

<asp:TextBox ID=”txtName” runat=”server”></asp:TextBox>

<br />

<br />

<asp:Button ID=”BtnSubmit” runat=”server” Text=”Submit”

onclick=”BtnSubmit_Click” />

<br />

<br />

<asp:GridView ID=”GridView1″ runat=”server”>

</asp:GridView>

<br />

</div>

</form>

</body>

</html>

Step2: Write the code behind page like this

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data;

using System.Data.SqlClient;

public partial class OutPutCaching : System.Web.UI.Page

{

SqlConnection con = new SqlConnection(“Data Source=.;Initial Catalog=Test;Integrated Security=True”);

protected void Page_Load(object sender, EventArgs e)

{

}

protected void BtnSubmit_Click(object sender, EventArgs e)

{

using (SqlCommand cmd = new SqlCommand(“Select *from tblEmp where EmpName=@EmpName”, con))

{

cmd.Parameters.AddWithValue(“@EmpName”, txtName.Text);

SqlDataAdapter da = new SqlDataAdapter(cmd);

DataTable dt = new DataTable();

da.Fill(dt);

if (dt.Rows.Count > 0)

{

GridView1.DataSource = dt;

GridView1.DataBind();

}

else

{

GridView1.DataSource = null;

GridView1.DataBind();

}

}

}

}

Then we will get the exact o/p while textbox field is  changing.

Fragment Caching

If we have to cache the portion of page then we can use fragment caching. This is mainly used if we have to display the advertisement on home page and one page refresh that image is changing.

Data Caching:

Data caching is the most flexible type of caching. If we have to load some data from database and we have to use that data frequently, then we can store that data in cache for some time period and use it repeatedly without calling the database. So it will reduce the server overload.

Sample code for data Caching:

Step1: In design page take one gridview and label control

Step2: Create some table with data for example tblEmp

Step3: Write the code in code behind for caching data in dataset like this

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data;

using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

GridView1.DataSource = getdataset();

GridView1.DataBind();

}

}

protected DataSet getdataset()

{

DataSet ds = (DataSet)Cache[“tblEmp”];

if (ds == null)

{

ds = EmpNameRetrival();

//caching for 10 secound

Cache.Insert(“tblEmp”, ds, null, DateTime.MaxValue, TimeSpan.FromSeconds(10));

Label1.Text = “Created and added to cache”;

}

else

{

Label1.Text = “Retrival from cache is happening”;

}

return ds;

}

protected DataSet EmpNameRetrival()

{

using(SqlConnection con=new SqlConnection(“Data Source=.;Initial Catalog=Test;Integrated Security=True”))

{

using (SqlCommand cmd = new SqlCommand(“Select top 10 *from tblEmp”, con))

{

SqlDataAdapter da = new SqlDataAdapter(cmd);

DataSet ds = new DataSet();

da.Fill(ds,”tblEmp”);

return ds;

}

}

}

}

Step4: Compile the project. Then you will get first time o/p  like this

After refress, you will get o/p like this

Advertisements

2 Responses to “Caching in asp.net”

  1. Sruthy Says:

    sir i’m a fresher wth a proj “send sms via asp.net”.i’ve seen ur comments dat u had succesfully got de code for de same.if u dont mind could u pls send me de entire code…..plss..ma mail id: sruthi.john.90@gmail.com

  2. Chandra Dev Says:

    Hi
    I have already posted the code in forum. Please check it on this link
    http://forums.asp.net/t/1191703.aspx


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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: