Thursday 11 June 2015

What is Caching in ASP.Net and How to implement DataSource Caching

Caching in ASP.Net
Caching is a technique by which we can improve the performance of our web-based application.
Advantage of Caching
•          Improve performance
•          Avoid time-consumption
•          Decrease hosting server round-trips
•          Decrease database server round-trips
•          Decrease network traffic
Disadvantage of Caching


  • Where data is different for each click that case caching is not supported Like inbox of GMAIL but you can store  data of Sensex
  • You can not store senstive data  in Chache





Types of Caching

  1.  DataSource Caching
  2. Pageoutput Caching
  3. Partial Page Caching
  4.  Data Caching
Where cache is stored..........................


  • Server
  • Client
  • Proxy Server


DataSource Caching: In this concept all data will be hold in data cache. Advantage of DataSource caching is that the Data Source controls automatically reload when the data is updated.
There are three type of cache in DataSource Caching
1. SqlDataSource
2. ObjectDataSource
3. XmlDataSource
LinqDataSource doesn’t support cache

-- sql query................................

create database test
use test
create table Student
(
RollNo int primary key,
Name varchar(50),
Course varchar(50)
)

1.   SqlDataSource Caching

Properties as SqlDataSource
·         EnableCaching,
·         CacheDuration
·         CacheExpirationPolicy
·         DataSourceMode

Module1: In this model updated table data show after chache duration.

Code for Default.aspx page.......................

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="RollNo" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="RollNo" HeaderText="RollNo" ReadOnly="True" SortExpression="RollNo" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Course" HeaderText="Course" SortExpression="Course" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
SelectCommand="SELECT * FROM [Student] ORDER BY [RollNo]"
CacheDuration="60" EnableCaching="True" CacheExpirationPolicy="Absolute">
</asp:SqlDataSource>
</div>
</form>
</body>
</html>

ByDefault cache is working with disConnected mode Dataset when you will select datareader you will find this type error. The data source 'SqlDataSource1' only supports caching when the data source's DataSourceMode is set to DataSet.

Note :  There are two type of  CacheExpirationPolicy in SqlDataSource Caching one is  Absolute and another is Sliding different b/w  both ,Absolute is using for store data in cache memory for a particular interval of time but It’s very important in case of data that does not changed often like your data change in once in every minute. When you are working with large data, then you should be used to sliding cache policy. Advantage of this policy is that data remains in cache as long as continues to be requested within particular interval of time.

Module2: When table data is updated automatically SqlDataSource control reload cache data from table.
Advantage of creating key dependency is that when sql table updated then, SqlDataSource automatically reload cache data without any cache duration.

First we will add Global.asax in our web-application put the below code in
<%@ Application Language="C#" %>

<script runat="server">

void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
HttpContext context = HttpContext.Current;
context.Cache.Insert ("CacheKey", DateTime.Now, null, DateTime.MaxValue,Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null);

}
...........................

Code for Default.aspx page.......................


<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="RollNo" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="RollNo" HeaderText="RollNo" ReadOnly="True" SortExpression="RollNo" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Course" HeaderText="Course" SortExpression="Course" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings: testConnectionString %>"
SelectCommand="SELECT * FROM [Student] ORDER BY [RollNo]"
EnableCaching="true"
CacheDuration="200"
CacheExpirationPolicy="Absolute"
CacheKeyDependency="CacheKey"
> 

</asp:SqlDataSource>
</div>
</form>

We are creating another webpage which name is AddNewStudent.aspx

Code for AddNewStudent.aspx page.......................

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
width: 100%;
}
.auto-style2 {
height: 23px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>

<table class="auto-style1">
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td class="auto-style2">RollNo</td>
<td class="auto-style2">
<asp:TextBox ID="txtRollNo" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Name</td>
<td>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Course</td>
<td>
<asp:TextBox ID="txtCourse" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>
<asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" Text="Save" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

Code for AddNewStudent.aspx.cs page.......................


using System;
using System.Data.SqlClient;

public partial class AddNewStudent : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnSave_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=USER;Initial Catalog=test;User ID=sa;Password=tiwari");
SqlCommand cmd = new SqlCommand("insert into Student values("+Convert.ToInt32(txtRollNo.Text)+",'"+txtName.Text+"','"+txtCourse.Text+"')",con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
// Cache.Insert("Cachekey", DateTime.Now);
Response.Write("Saved");
}
}

 2.    ObjectDataSource Caching

        EnableCaching,
·         CacheDuration
·         CacheExpirationPolicy
·         DataSourceMode
·         TypeName
·         SelectMethod

We will take a seperate class for ObjectDataSource Caching which name is Student class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
// using this name sapce
using System.Configuration;
using System.Data;
using System.Data.SqlClient;


public class Student
{
public static DataTable StudentData()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["testConnectionString"].ToString());
DataTable dt = new DataTable();
con.Open();
SqlDataAdapter da = new SqlDataAdapter("Select * from Student", con);
da.Fill(dt);
con.Close();

return dt;
}
}
Code for  Default2.aspx page.......................


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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:GridView ID="GridView1" runat="server" DataSourceID="ObjectDataSource1">
</asp:GridView>

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
TypeName="Student"
SelectMethod="StudentData"
EnableCaching="true"
CacheExpirationPolicy="Absolute"
CacheDuration="15">
</asp:ObjectDataSource>
</div>
</form>
</body>
</html>
3.XmlDataSource Caching
XmlDataSource contains same properties as SqlDataSource and ObjectDataSource but XmlDataSource cache by default and it’s automatically creates file dependency on attached xml file, means when xml file is modified, its automatically reloads data.


Step 1: we will take anoher Folder which name is Data in our WebApplication and create a xml which name is StuXml.xml

Code for StuXml.xml file...................

<?xml version="1.0" encoding="utf-8" ?>
<Students>
<Student RollNo="1" Name="Somesh Katiyar" Course="B.Tech" City="Kanpur" MobileNo="9911992345" />
<Student RollNo="2" Name="Manoj Yadav" Course="M.A." City="Ballia" MobileNo="3411992345" />
<Student RollNo="3" Name="Kush Tiwari" Course="Mca" City="Varanasi" MobileNo="7711992345" />
<Student RollNo="4" Name="Udayan Maiti" Course="M.Tech" City="Kolkatta" MobileNo="9900992345" />
<Student RollNo="5" Name="Vinay Singh" Course="B.A" City="Noida" MobileNo="9911789234" />
</Students>

Code for Default3.aspx page.......................

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" DataSourceID="XmlDataSource1" >
</asp:GridView>

<asp:XmlDataSource ID="XmlDataSource1" runat="server"
DataFile="~/Data/StuXml.xml">
</asp:XmlDataSource>
</div>
</form>
</body>
</html>


Result


0 comments:

Post a Comment