How the das Blog Cache Engine Works (And a Caching tip in General)
Clemens and I may disagree on SQL Server v XML storage, but the das Blog Cache engine is real simple and we agree on it. What we do is cache the main page for 1 day (86400 seconds). We also varybyparam for the date and none. This way the page will stay in cache for either 1 day or until it is edited again (via a comment or an addition blog entry.)
I was putting together some samples for the MDC in Cairo next week and made a real simple page that caches a page based on the query string (varybyparam) and a file dependency (an XML file). Here is an example in a simple page using an ASP .NET datagrid against Northwind:
<%@ Page language="c#" Codebehind="Cache_VaryByParam_Filedep.aspx.cs" AutoEventWireup="false" Inherits="DataGridCSharp.CachingDataGridFile" %>
<%@ OutputCache duration="86400" varybyparam="CustomerID" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>CachingDataGrid</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<asp:DataGrid id="DataGrid1" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 72px" runat="server"></asp:DataGrid>
<asp:Label id="Label1" style="Z-INDEX: 102; LEFT: 24px; POSITION: absolute; TOP: 40px" runat="server"
Width="440px">Label</asp:Label>
</form>
</body>
</HTML>
Then all we do is add a file dependency, in the case of das Blog it is the actual XML file that stores the data. This way the page will stay in cache for either 1 day or until it is edited again (via a comment or an addition blog entry.) Here is the code behind for the simple Northwind example from above.
private void Page_Load(object sender, System.EventArgs e)
{
//we are setting the OutputCache to 1 day and the varybyparam for the querystring
//<%@ OutputCache duration="86400" varybyparam="CustomerID" %>
//override the cache if this file changes
Response.AddFileDependency(Server.MapPath("Contacts.xml"));
Label1.Text="Page Generated At: " + System.DateTime.Now.ToString();
// simple databinding for testing
SqlConnection conn =new SqlConnection("server=(local);uid=sa;pwd=;database=Northwind");
//open the connection
conn.Open();
//can set a command to a SQL text and connection
SqlCommand cmd = new SqlCommand("Select * From Orders Where CustomerID='" + Request.QueryString["CustomerID"] +"'", conn);
SqlDataReader dr;
//open a datareader
dr = cmd.ExecuteReader(CommandBehavior.Default);
//do the databinding
DataGrid1.DataSource = dr;
DataGrid1.DataBind();
}