Escolar Documentos
Profissional Documentos
Cultura Documentos
NET - Caching
Rakesh Singh
NARESH I TECHNOLOGIES Hyderabad
0
Advantages of Caching:
1. Reduce hosting server round-trips
When content is cached at the client or in proxies, it cause minimum request to server.
2. Reduce database server round-trips
When content is cached at the web server, it can eliminate the database request.
3. Reduce network traffic
When content is cached at the client side, it also reduce the network traffic.
4. Avoid time-consumption for regenerating reusable content
When reusable content is cached, it avoid the time consumption for regenerating reusable content.
5. Improve performance
Since cached content reduce round-trips, network traffic and avoid time consumption for regenerating
reusable content which cause a boost in the performance.
Types of Caching:
The ASP.NET Web Application Framework supports the following types of caching:
Data Caching
Page output caching provides two models for page caching: Full-Page Caching (Page Level Caching) and Partial-Page
Caching (Fragment Caching). Full-page caching persists the complete contents of a page and uses the cached page content
to fulfil client requests. Partial-page caching persists specified portions of a page and lets other portions of the page be
created dynamically.
The page level output caching can be done using @OutputCache directive. It stores complete response of page output into
the memory (Server Memory)
@ OutputCache Directive:
Attributes:
Duration - It is used to define the time in seconds to cache the page response in memory.
VaryByParam: It is used to set the value to get Single Response or Multiple Response.
Ex:
<%@ OutputCache Duration="60" VaryByParam="None" %>
The Duration parameter specifies how long, in seconds, the HTML output of the Web page should be held in the cache.
When the duration expires, the cache becomes invalid and, with the next visit, the cached content is flushed, the ASP.NET
Web page's HTML dynamically generated, and the cache repopulated with this HTML.
The VaryByParam parameter is used to indicate whether any GET (QueryString) or POST (via a form submit
with method="POST") parameters should be used in varying what gets cached. In other words, multiple versions of a
page can be cached if the output used to generate the page is different for different values passed in via either a GET or
POST.
Example1:
Create an aspx page to show the server date time as well as client date time but store server-side date time response in
memory using OutputCache with a specified duration in seconds. So when we make a request to access that particular
page first time it goes through entire application process & cached in memory, then send to client machine but when we
make next time request it doesnt go through the entire application process as it was already stored in memory. So it just
gives output from the memory itself but if the specified time duration expired then again start through the entire application
process.
Design View:
Source View:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CachingEx1.aspx.cs" Inherits="CachingEx1" %>
<%@ OutputCache Duration="60" VaryByParam="none" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>RakeshDotNet-Caching Example</title>
</head>
<body>
<form id="form1" runat="server">
<div style="border:5px solid green;text-align:center">
<h3>Server - Side Date Time:
<asp:Label ID="Label1" runat="server">
</asp:Label>
</h3>
<br />
<h3>Client - Side Date Time:
<script type="text/javascript">
document.write(Date());
</script>
</h3>
</div>
</form>
</body>
</html>
Code View:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class CachingEx1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(5000);
Label1.Text = DateTime.Now.ToString();
}
}
Example2: Working with VaryByParam Attributes to get multiple responses from the memory via control request.
Design View:
Source View:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CachingEx2.aspx.cs" Inherits=" CachingEx2" %>
<%@ OutputCache Duration="60" VaryByParam="ddlDept" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>RakeshDotNet-Caching Example</title>
</head>
<body>
<form id="form1" runat="server">
<div style="border: 5px solid green;text-align:center">
<b>Select Dept: </b>
<asp:DropDownList ID="ddlDept" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="ddlDept_SelectedIndexChanged"></asp:DropDownList>
<br />
<asp:GridView ID="GridView1" runat="server" Width="100%" EmptyDataText="No Employee Data Available">
</asp:GridView>
<br />
<h3>
<asp:Label ID="Label1" runat="server"></asp:Label></h3>
<br />
<h3>
<b>Client - Side DateTime:</b>
<script type="text/javascript">
document.write(Date());
</script>
</h3>
</div>
</form>
</body>
</html>
Code View:
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 CachingEx2 : System.Web.UI.Page
{
SqlConnection cn = null;
SqlDataAdapter da = null;
DataSet ds = null;
string strSqlQuery = String.Empty;
protected void Page_Load(object sender, EventArgs e)
{
cn = new SqlConnection("Data Source=(local);Database=DemoDB;User Id=sa;Password=123");
if (!Page.IsPostBack)
{
BindDeptDDL();
BindEmpData(ddlDept.SelectedItem.Value);
}
}
void BindDeptDDL()
{
strSqlQuery = "Select * from Dept";
da = new SqlDataAdapter(strSqlQuery, cn);
ds = new DataSet();
da.Fill(ds, "Dept");
ddlDept.DataSource = ds.Tables["Dept"];
ddlDept.DataTextField = "DeptName";
ddlDept.DataValueField = "DeptId";
ddlDept.DataBind();
ddlDept.Items.Insert(0, new ListItem("All", "0"));
}
void BindEmpData(string deptId)
{
if (deptId == "0")
{
strSqlQuery = "Select * from Emp";
}
else
{
strSqlQuery = "Select * from Emp Where DeptId=" + deptId;
}
Source View:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CachingEx3.aspx.cs" Inherits="CachingEx3" %>
<%@ OutputCache Duration="60" VaryByParam="DeptId" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>RakeshDotNet-Caching Example</title>
</head>
<body>
<form id="form1" runat="server">
<div style="border: 5px solid green; text-align: center">
<b>Click Any of Following Below Dept:</b>
<br />
<asp:BulletedList ID="BulletedList1" runat="server" DisplayMode="HyperLink">
</asp:BulletedList>
<asp:GridView ID="GridView1" runat="server" Caption="Employee Data" EmptyDataText="No Employee
Available!!!" EmptyDataRowStyle-ForeColor="Red" Width="100%">
</asp:GridView>
<h3>
<asp:Label ID="Label1" runat="server" /></h3>
<h3>Client - Side Date & Time:
<script type="text/javascript">
document.write(Date());
</script>
</h3>
</div>
</form>
</body>
</html>
Code View:
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 CachingEx3 : System.Web.UI.Page
{
SqlConnection cn = null;
SqlDataAdapter da = null;
DataSet ds = null;
string strSqlQuery = String.Empty;
protected void Page_Load(object sender, EventArgs e)
{
cn = new SqlConnection("Data Source=(local);Database=DemoDB;User Id=sa;Password=123");
if (!Page.IsPostBack)
{
BindDeptBulletedList();
if (Request.QueryString["DeptId"] != null)
{
BindEmpByDept();
}
}
void BindDeptBulletedList()
{
strSqlQuery = "Select * from Dept";
da = new SqlDataAdapter(strSqlQuery, cn);
ds = new DataSet();
da.Fill(ds, "Dept");
DataRowCollection drc = ds.Tables["Dept"].Rows;
foreach (DataRow dr in drc)
{
BulletedList1.Items.Add(new ListItem(dr["DeptName"].ToString(),"~/CachingEx3.aspx?DeptId=" +
dr["DeptId"].ToString()));
}
}
void BindEmpByDept()
{
System.Threading.Thread.Sleep(5000);
string deptId = Request.QueryString["DeptId"].ToString();
strSqlQuery = "Select * from Emp Where DeptId=" + deptId;
da = new SqlDataAdapter(strSqlQuery, cn);
ds = new DataSet();
da.Fill(ds, "Emp");
GridView1.DataSource = ds.Tables["Emp"];
GridView1.DataBind();
}
2. Fragment Caching
Partial-Page Output Caching, or page fragment caching, allows specific regions of pages to be cached. ASP.NET provides
a way to take advantage of this powerful technique, requiring that the part(s) of the page you wish to have cached appear
in a User Control. One way to specify that the contents of a User Control should be cached is to supply
an OutputCache directive at the top of the User Control. That's it! The content inside the User Control will now be cached
for the specified period, while the ASP.NET Web page that contains the User Control will continue to serve dynamic content.
(Note that for this you should not place an OutputCache directive in the ASP.NET Web page that contains the User Control
- just inside of the User Control.)
Fragment caching refers to the caching of individual user controls within a Web Form. Each user control can have
independent cache durations and implementations of how the caching behaviour is to be applied. Fragment caching is
useful when you need to cache only a subset of a page.
Fragment caching allows to cache specific portions of the page rather than the whole page. It is done by implementing
the page in different parts by creating everything in form of user controls and caching each user control individually.
Example1: We use fragment caching in a situation where we dont want to store response of whole page in memory,
instead of this we may want to store some portion of a page in memory. So to do this we may take the help of Web User
Control and OutputCache Directive in web user control only, not in an aspx page.
Create a Web User Control (ucCaching.ascx) that display the server date time and store into the memory for the next 30
seconds using OutputCache Directive as following:
Design View:
Source View:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CachingEx4.aspx.cs" Inherits=" CachingEx4" %>
<%@ Register Src="~/ucCaching.ascx" TagName="ucCaching" TagPrefix="uc1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table border="0">
<tr>
<td width="50%">
<h1>Server Date & Time From Page:
<br />
<asp:Label ID="lblDateTime" runat="server" />
</h1>
</td>
<td width="50%">
<uc1:ucCaching ID="ucCaching1"
runat="server" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Code View:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class CachingEx4 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblDateTime.Text = DateTime.Now.ToString();
}
}
3. Data Caching
In simple terms data caching is storing data in memory for quick access. Typically information that is costly to
obtain (in terms of performance) is stored in the cache. One of the more common items stored in a cache in a
Web application environment is commonly displayed database values; by caching such information, rather than
relying on repeated database calls, the demand on the Web server and database server's system resources are
decreased and the Web application's scalability increased. As Microsoft articulately puts it, "Caching is a
technique widely used in computing to increase performance by keeping frequently accessed or expensive data
in memory. In the context of a Web application, caching is used to retain pages or data across HTTP requests
and reuse them without the expense of recreating them."
OR
Data caching means caching data from a data source. As long as the cache is not expired, a request for the
data will be fulfilled from the cache. When the cache is expired, fresh data is obtained by the data source and
the cache is refilled.
Caching enables you to store data in memory for rapid access. Applications can access the cache and not have
to retrieve the data from the original source whenever the data is accessed. This avoids repeated queries for
data, and it can improve performance and scalability.
Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.
P a g e | 11
OR
Data Cache is used to storing frequently used data in the Cache memory. It's much efficient to retrieve data from the data
cache instead of database or other sources. We need use System.Web.Caching namespace. The scope of the data caching
is within the application domain unlike "Session". Every user can able to access this objects.
How Data Caching Works?
When client request to the server, server execute the stored procedure or function or select statements on the
Sql Server Database then it returns the response to the browser. If we run again, same process will happen on
the web server with Sql Server.
In the very first time retrieve the records from the Sql Server Database and stored into the Cache memory. After
that records will retrieve from Cache memory (IIS). We can set expiration period time after expiration time over
the caching again it will hit the Sql Server database and stored into the cache memory and next retrieve will
happen on the data cache memory.
Example1:
Source View:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CachingEx5.aspx.cs" Inherits=" CachingEx5" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>RakeshDotNet Caching Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblInfo" runat="server" />
<br />
<br />
<asp:Button ID="btnRefresh" runat="server" Text="Refresh" />
</div>
</form>
</body>
</html>
Code View:
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.UI;
System.Web.UI.WebControls;
using System.Web.Caching;
public partial class CachingEx5 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
lblInfo.Text += "Page Created With Post Back.<br/>";
}
else
{
lblInfo.Text += "Page Created Without PostBack.<br/>";
}
if (Cache["TestItem"] == null)
{
lblInfo.Text += "Creating Test Item.<br/>";
DateTime testItem = DateTime.Now;
lblInfo.Text += "Storing test item in cache for 60 seconds.<br/>";
Cache.Insert("TestItem", testItem,null,
DateTime.Now.AddSeconds(60), TimeSpan.Zero);
}
else
{
lblInfo.Text += "Retrieving Test Item.<br/>";
DateTime testItem = (DateTime)Cache["TestItem"];
lblInfo.Text += "Displaying Stored Date & Time From Cache: " + testItem.ToString();
}
lblInfo.Text += "<br />";
}
Example2:
Design View (CachingEx6.aspx):
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default9.aspx.cs" Inherits="Default9"
%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>RakeshDotNet Caching Example</title>
</head>
<body>
<form id="form1" runat="server">
<div style="border: 5px solid green; text-align: center">
<asp:GridView ID="GridView1" runat="server" Caption="Employee Data" EmptyDataText="No
Employee Available!!!" EmptyDataRowStyle-ForeColor="Red" Width="100%">
</asp:GridView>
<br />
<asp:Label ID="lblDateTime" runat="server"></asp:Label>
<br />
<asp:Button ID="btnRefresh" runat="server" Text="Refresh" />
</div>
</form>
</body>
</html>
Code View:
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;
using System.Configuration;
using System.Web.Caching;
public partial class Default9 : System.Web.UI.Page
{
SqlConnection cn = null;
SqlDataAdapter da = null;
DataSet ds = null;
protected void Page_Load(object sender, EventArgs e)
{
cn = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
if (Cache["EmpData"] == null)
{
da = new SqlDataAdapter("Select * from Emp", cn);
ds = new DataSet();
da.Fill(ds, "Emp");
Cache.Insert("EmpData", ds, null,
DateTime.Now.AddSeconds(30), TimeSpan.Zero);
lblDateTime.Text = "Data Fetched At: " + DateTime.Now.ToString();
GridView1.DataSource = ds.Tables["Emp"];
GridView1.DataBind();
}
else
{
DataSet dsEmp = (DataSet)Cache["EmpData"];
GridView1.DataSource = dsEmp.Tables["Emp"];
GridView1.DataBind();
}
}
}
Conclusion:
Caching is a technique that definitely improves the performance of web applications if one is careful to have a balance in
terms of which data needs to be cached and parameter values for expiration policy.