Lab: Combining Caching at Multiple Levels

Lab: Combining Caching at Multiple Levels

In this lab, you ll optimize a Web application by using caching to:

  • Store multiple responses from a single Web form in the server s memory

  • Save an application-wide customer list generated from a query to a SQL database

  • Save customer order information in a cached data set

You ll also use the Performance Logs and Alerts snap-in to monitor caching within the deployed application. When complete, the application will appear as shown in Figure 12-2.

figure 12-2 the cachinglab.aspx web form

Figure 12-2. The CachingLab.aspx Web Form

Estimated lesson time: 20 minutes

Exercise 1: Cache Multiple Versions of the Web Form

In this exercise, you ll create a Web form that displays a list of customers from the Northwind Traders database. Users can select a customer from a drop-down list and click a button to view a list of orders in a data grid.

To minimize the number of times each request must be processed on the server, you will cache the Web form for 1 minute. Because the drop-down list can vary the response, you will use the VaryByParam attribute to store multiple responses from the Web form.

To create the Web form

  1. Add a Web form named CachingLab.aspx to your application, and make that page the start page for your application.

  2. Create DropDownList, DataGrid, and Button controls on the Web form, as shown in the following HTML:

    <HTML> <body> <form  method="post" runat="server"> <h2>Lab: Combining Caching at Multiple Levels</h2> <hr> <asp:dropdownlist  runat="server"  Width="496px"></asp:dropdownlist> <asp:button  runat="server"  Text="Get Orders"></asp:button> <asp:datagrid id=grdOrders runat="server" Width="80%"  DataSource="<%# dsOrders %>" Height="160px" BorderColor="#CCCCCC"  BorderStyle="None" BorderWidth="1px" BackColor="White"  CellPadding="3"> <SelectedItemStyle Font-Bold="True" ForeColor="White"  BackColor="#669999"></SelectedItemStyle> <ItemStyle ForeColor="#000066"></ItemStyle> <HeaderStyle Font-Bold="True" ForeColor="White"  BackColor="#006699"></HeaderStyle> <FooterStyle ForeColor="#000066"  BackColor="White"></FooterStyle> <PagerStyle HorizontalAlign="Left" ForeColor="#000066"  BackColor="White" Mode="NumericPages"></PagerStyle> </asp:datagrid> </body> </HTML>

  3. Add the following OutputCache directive to the top of the Web form:

    <%@ OutputCache Duration="60" VaryByParam="drpCustList" Location="Any" %>

    The preceding directive caches a separate response for each different selection from the drop-down list. Responses are cached for 60 seconds each and can be stored at any location that accepts caching.

Exercise 2: Cache a Customer List

In this exercise, you ll populate the Web form s drop-down list of customers and store the resulting list in the Cache object. Even though the customer list is already cached as part of the Web form in the preceding exercise, caching the customer list separately makes the data available to other parts of the application that might require it. Also, because the customer list changes infrequently, that item can have a longer expiration time than the Web form.

To populate the customer list and store the data in the cache

  1. Add the following code to the CachingLab Web form s Load event procedure to check whether the customer list exists in the cache and to populate the drop-down list from the cached list:

    Visual Basic .NET

    Protected CustList As New ListItemCollection Protected NWindDSN As String = "data source=(local); " + _ "initial catalog=Northwind;integrated security=SSPI;" + _  "persist security info=True;workstation id=WOMBAT2;packet size=4096" Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' The first time the page is displayed... If Not IsPostBack Then ' If the customer list isn't already cached... If IsNothing(Cache("CustList")) Then ' Cache the customer list. CacheCustList() Else ' Otherwise, get the list from cache. CustList = Cache("CustList") End If ' Add items to the drop-down list. Dim itmCustList As ListItem For Each itmCustList In CustList drpCustList.Items.Add(itmCustList) Next End If End Sub

    Visual C#

    protected ListItemCollection CustList = new ListItemCollection(); protected string NWindDSN = "data source=(local); initial catalog=Northwind;integrated security=SSPI; persist security info=True;workstation id=WOMBAT2;packet size=4096"; private void Page_Load(object sender, System.EventArgs e) { // The first time the page is displayed... if (!IsPostBack) { // If the customer list isn't already cached... if (Cache["CustList"]==null) // Cache the customer list. CacheCustList(); else // Otherwise, get the list from cache. CustList = (ListItemCollection)Cache["CustList"]; // Add items to the drop-down list. foreach (ListItem itmCustList in CustList) drpCustList.Items.Add(itmCustList); } }

  2. Add the following code to get the customer list from the Northwind Traders database and add the list to the cache:

    Visual Basic .NET

    Sub CacheCustList() ' Create a SQL database connection. Dim connNWind As New SqlConnection(NWindDSN)) ' Command to get customer names and IDs. Dim cmdCustList As New SqlCommand("Select CustomerID, " + _  "CompanyName From Customers Order By CompanyName", connNWind) Dim drCustList As SqlDataReader ' Open connection. connNWind.Open() Try drCustList = cmdCustList.ExecuteReader Do While drCustList.Read CustList.Add(New ListItem(drCustList.GetValue(1), _ drCustList.GetValue(0))) Loop ' Cache the item for 5 minutes with sliding expiration and a high ' priority. Cache.Add("CustList", CustList, Nothing,_ Cache.NoAbsoluteExpiration, _ System.TimeSpan.FromMinutes(5),_ Caching.CacheItemPriority.High, _ Nothing) Catch ex As Exception Response.Write("An error occurred: " + ex.Message) Finally connNWind.Close() End Try End Sub

    Visual C#

    void CacheCustList() { // Create a SQL database connection. SqlConnection connNWind = new SqlConnection(NWindDSN); // Command to get customer names and IDs. SqlCommand cmdCustList = new SqlCommand("Select CustomerID, " +  "CompanyName From Customers Order By CompanyName", connNWind); SqlDataReader drCustList; // Open connection. connNWind.Open(); try { drCustList = cmdCustList.ExecuteReader(); while( drCustList.Read()) { CustList.Add(new ListItem(drCustList.GetValue(1).ToString(), drCustList.GetValue(0).ToString())); } // Cache the item for 5 minutes with sliding expiration //and high priority. Cache.Add("CustList", CustList, null, Cache.NoAbsoluteExpiration, System.TimeSpan.FromMinutes(5), CacheItemPriority.High, null); } catch(Exception ex) { Response.Write("An error occurred: " + ex.Message); } finally { connNWind.Close(); } }

The preceding Cache object Add method adds the customer list using sliding expiration and a high priority. Those settings help ensure that the customer list remains cached practically indefinitely if the item is frequently accessed.

Exercise 3: Cache Data from a Stored Procedure

In this exercise, you ll cache data sets containing lists of customer orders. Again, you could rely on the Web form cache settings to store this data, but caching the data sets separately makes them available for other uses within the application, and using sliding expiration means that frequently used customer order lists are more likely to be served from the cache than from the database.

To cache the customer order data sets

  1. Add the following code to the CachingLab Web form s butGetOrders_Click event procedure to check whether the customer order data set exists in the cache, to retrieve the data set from the cache, and to display the data set in the DataGrid control:

    Visual Basic .NET

    ' Public variable for databinding to DataGrid. Public disorders As DataSet Private Sub butGetOrders_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butGetOrders.Click dsOrders = New DataSet ' If the customer list isn't already cached... If IsNothing(Cache(drpCustList.SelectedItem.Value)) Then ' Cache the customer list. CacheOrders() Else ' Otherwise, get the list from cache. dsOrders = Cache(drpCustList.SelectedItem.Value) End If ' Bind the grid to display the orders. grdOrders.DataBind() End Sub

    Visual C#

    // Public variable for databinding to DataGrid. public DataSet dsOrders = new DataSet(); private void butGetOrders_Click(object sender, System.EventArgs e) { DataSet dsOrders = new DataSet(); // If the customer list isn't already cached... if (Cache[drpCustList.SelectedItem.Value]==null) // Cache the customer list. CacheOrders(); else // Otherwise, get the list from cache. dsOrders = (DataSet)Cache[drpCustList.SelectedItem.Value]; // Bind the grid to display the orders. grdOrders.DataBind(); }

  2. Add the following code to get the data set from the Northwind Traders database and to add the data set to the cache:

    Visual Basic .NET

    Sub CacheOrders() ' Connection string for database. Dim connNWind As New SqlConnection(NWindDSN) ' Command for stored procedure. Dim cmdOrders As New SqlCommand("CustOrdersOrders", connNWind) cmdOrders.Parameters.Add(New SqlParameter("@CustomerID", _ drpCustList.SelectedItem.Value)) ' Set the command properties. cmdOrders.CommandType = CommandType.StoredProcedure Dim adptOrders As New SqlDataAdapter(cmdOrders) Try ' Excecute the stored procedure. adptOrders.Fill(dsOrders) Catch ex As Exception Response.Write("An error occurred: " + ex.Message) End Try ' Cache the item for 1 minute with sliding expiration and default priority. Cache.Add(drpCustList.SelectedItem.Value, dsOrders, Nothing, _ Cache.NoAbsoluteExpiration, System.TimeSpan.FromMinutes(1), _ Caching.CacheItemPriority.Default, Nothing) End Sub

    Visual C#

    void CacheOrders() { // Connection string for database. SqlConnection connNWind = new SqlConnection(NWindDSN); // Command for stored procedure. SqlCommand cmdOrders = new SqlCommand("CustOrdersOrders", connNWind); cmdOrders.Parameters.Add(new SqlParameter("@CustomerID", drpCustList.SelectedItem.Value)); // Set the command properties. cmdOrders.CommandType = CommandType.StoredProcedure; SqlDataAdapter adptOrders = new SqlDataAdapter(cmdOrders); try { // Excecute the stored procedure. adptOrders.Fill(dsOrders); } catch (Exception ex ) { Response.Write("An error occurred: " + ex.Message); } // Cache the item for 1 minute with sliding expiration and default // priority. Cache.Add(drpCustList.SelectedItem.Value, dsOrders, null, Cache.NoAbsoluteExpiration, System.TimeSpan.FromMinutes(1), CacheItemPriority.Default, null); }

The preceding code creates the data set using a stored procedure for greater efficiency. You can play with the cache duration of the orders data set to see the effect on performance.

Exercise 4: Test Cache Performance

In this exercise, you ll use the Performance Logs and Alerts snap-in to monitor the performance of the application you created in the preceding exercises.

To test the application s performance

  1. Build and deploy the CachingLab application. You can deploy the application to your local machine or to a test server for convenience.

  2. Start the MMC Performance Logs and Alerts snap-in.

  3. Add the following performance counters for the application at its deployed location:

    • Requests/Sec.

    • Cache API Entries

    • Cache API Hit Ratio

    • Cache Total Turnover Rate

    • OutputCache Entries

    • OutputCache Hit Ratio

  4. Use ACT to load-test the application. See Chapter 10, Testing Web Applications, for instructions on using ACT.

    Figure 12-3 shows the results from the snap-in after load testing.

    figure 12-3 cachinglab performance

    Figure 12-3. CachingLab Performance

  5. Optionally, adjust the duration settings for the cached Web form, customer list, and order data set to see their effect on performance.



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[.  .. ]0-315
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[. .. ]0-315
ISBN: N/A
EAN: N/A
Year: 2003
Pages: 118

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net