O'Reilly logo

ADO.NET Cookbook by Bill Hamilton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

9.3. Caching Data

Problem

Given a Web Forms application that is performing poorly because it is repeatedly reading data that doesn’t change very often, you need to cache the data to eliminate unnecessary queries and improve the performance.

Solution

Use the ASP.NET Cache class.

The Web Forms page defines the data grid used to display the contents of a DataSet, a button to clear the cache, and a label that displays whether the data was retrieved from the cache or from the database. The code for the Web Forms page is shown in Example 9-3.

Example 9-3. File: ADOCookbookCS0903.aspx

<form id="ADOCookbookCS0903" method="post" runat="server">
    <asp:HyperLink id="HyperLink1"
        style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 24px"
        runat="server" NavigateUrl="default.aspx">Main Menu
    </asp:HyperLink>
    <asp:DataGrid id="customersDataGrid"
        style="Z-INDEX: 102; LEFT: 16px; POSITION: absolute; TOP: 128px"
        runat="server" AllowPaging="True">
        <HeaderStyle Font-Bold="True"></HeaderStyle>
    </asp:DataGrid>
    <asp:Label id="cacheStatusLabel"
        style="Z-INDEX: 103; LEFT: 16px; POSITION: absolute; TOP: 96px"
        runat="server" ForeColor="Green"></asp:Label>
    <asp:Button id="clearCacheButton"
        style="Z-INDEX: 104; LEFT: 16px; POSITION: absolute; TOP: 56px"
        runat="server" Text="Clear Cache">
    </asp:Button>
</form>

The code-behind contains three event handlers and two methods:

Page.Load

Checks the cache for an object with the key CustomerDataSet. If an entry is not found, the DataSet is loaded by calling the LoadDataSet( ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required