Object Caching File Dependency : File Dependency « Cache « ASP.NET Tutorial






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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Object Caching</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h1>Object Caching</h1>
    <h2>File Dependency</h2>
     <asp:Label ID="lblMessage" runat="server" />
     <br />
     <br />
     <asp:GridView ID="gv" runat="server" />
     <br />
     <asp:Button ID="btnClear" runat="server" Text="Clear Cache" OnClick="btnClear_Click" />
     <asp:Button ID="btnPost" runat="server" Text="Post" />
    </div>
    </form>
</body>
</html>

File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Caching;      
using System.Xml;          

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

   private void CreateGridView()
   {
     DataSet dsGrid;
     dsGrid = (DataSet)Cache["GridViewDataSet"];
     if (dsGrid == null)
     {
       dsGrid = GetDataSet();
       CacheDependency fileDepends = new CacheDependency(Server.MapPath("NorthWind.xml"));
       Cache.Insert("GridViewDataSet", dsGrid, fileDepends);
       lblMessage.Text = "Data from XML file.";
     }
     else
     {
       lblMessage.Text = "Data from cache.";
     }

     gv.DataSource = dsGrid.Tables[0];
     gv.DataBind();
   }

   private DataSet GetDataSet()
   {
     DataSet dsData = new DataSet();
     XmlDataDocument doc = new XmlDataDocument();
     doc.DataSet.ReadXml(Server.MapPath("NorthWind.xml"));
     dsData = doc.DataSet;
     return dsData;
   }

  protected void btnClear_Click(object sender, EventArgs e)
   {
      Cache.Remove("GridViewDataSet");
    CreateGridView();
   }
 }
 
File: NorthWind.xml

<?xml version="1.0" encoding="UTF-16" ?>
<ROOT>
  <Customers CustomerID="A" CompanyName="A" ContactName="Dan" ContactTitle="Sales" Address="Str. 57" City="Berlin" PostalCode="11111" Country="Germany" Phone="030-0074321" Fax="030-0076545" /> 
  <Customers CustomerID="B" CompanyName="B" ContactName="Ana" ContactTitle="Owner" Address="Road 22" City="New York" PostalCode="00000" Country="Mexico" Phone="(555) 555-4729" Fax="(5) 555-3745" /> 
</ROOT>








13.6.File Dependency
13.6.1.Creating a Page Output Cache File Dependency
13.6.2.Object Caching File Dependency