In my previous article, I explained about Caching techniques in Asp.Net. But there are some situations where we need to remove the cache data based on some conditions.
For example we are using the output caching for some asp.net page which displays the employee data from some XML file as shown below.
Default.aspx page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ OutputCache Duration="9999" VaryByParam="none" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div align="center">
<asp:GridView ID="gv1" runat="server"></asp:GridView>
</div>
</form>
</body>
</html>
Default.aspx.cs page:
protected void Page_Load(object sender, EventArgs e)
{
BindData();
}
private void BindData()
{
try
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("Employee.xml"));
gv1.DataSource = ds.Tables[0].DefaultView;
gv1.DataBind();
}
catch (Exception ex)
{
}
}
But, we have to refresh the page whenever the xml file changed. That means if we add some new employee or if we remove the existing employee, we have to load the page with the fresh data. In Asp.Net 2.0, we don’t have any such type of facility. We can do this by using AddFileDependency in Asp.Net 3.5 as shown below.
protected void Page_Load(object sender, EventArgs e)
{
Response.AddFileDependency(Server.MapPath("Employee.xml"));
BindData();
}
private void BindData()
{
try
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("Employee.xml"));
gv1.DataSource = ds.Tables[0].DefaultView;
gv1.DataBind();
}
catch (Exception ex)
{
}
}
If we add the Response.AddFileDependency(Server.MapPath("Employee.xml")); code in Page_Load event, the cache data will replace by latest data if there is any data change in Employee.xml file.