Caching Made Simple - A Practical Birdseye Overview
page 6 of 8
by Michael Libby
Feedback
Average Rating: 
Views (Total / Last 10 Days): 33211/ 42

How to Use Output Caching

Output Caching Overview

Output caching can be set programmatically using the HttpCachePolicy class, or declaratively by using the OutputCache page or control directive. The primary attributes for output caching are as follows:

  Attribute Description
  Duration The time, in seconds, that a page will be cached at the client. Sliding expiration can be set programmatically for server-side cache using the SetSlidingExpiration() method of the HttpCachePolicy class.
  Location The location where the page or user control will be cached. Values can be Any (the default value, caching can be wherever applicable, i.e. the client browser, proxy server, or Web server), Client, Downstream (client or proxy server), None (no caching), and Server.
  VaryByCustom  A string that indicates either the browser or custom string that is used to vary cache.
Note: This parameter can only be used in server-side cache.
  VaryByHeader  A semicolon delimited list of HTTP headers for which to vary the output cache.
Note: This attribute only applies to server-side cache and must be used with the Duration attribute.
  VaryByParam  A semicolon delimited list of parameters for which to vary output cache.

Note that the Output directive requires two parameters: VaryByParam and Duration. If VaryByParam does not apply then set its value to None. Output caching at the client is retrieved only by the page’s URL and not the page’s version, thus VaryByCustom, VaryByHeader, and VaryByParam apply only to server-side cache.

Examples of using these attributes would be as follows:

Caching at proxy servers and the client:

Page Directive Approach

<%@ OutputCache Duration="3600" Location="Downstream" VaryByParam="None" %>

Programmatic Approach

Response.Cache.SetExpires(DateTime.Now.AddSeconds(3600));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetNoServerCaching();

Caching variations of a page at the server based on browser type:

Page Directive Approach

<%@ OutputCache Duration="3600" VaryByHeader="User-Agent" VaryByParam="None" %>

Programmatic Approach

Response.Cache.SetExpires(DateTime.Now.AddSeconds(3600));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.VaryByHeaders["User-Agent"] = true;

Caching variations of a page based upon a DropDownList control’s selection:

Page Directive Approach

<%@ OutputCache duration="3600" VaryByParam="ddlControl"%>

Programmatic Approach

Response.Cache.SetExpires(DateTime.Now.AddSeconds(3600));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.VaryByParams["ddlControl"] = true;

Caching variations of a page at the server based upon strings:

Page Directive Approach

<%@ OutputCache duration="3600" VaryByParam="None" VaryByCustom="MyVersion""%>

Programmatic Approach

Response.Cache.SetExpires(DateTime.Now.AddSeconds(3600));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetVaryByCustom("MyVersion");

Note: The string, MyVersion, is actually replaced in the global.asax file by overriding method GetVaryByCustomString. For example:

public override string GetVaryByCustomString(HttpContext context, string arg) {
   if (arg == "MyVersion") {
      return "Version=" + SomeString;
   }
   return SomeOtherString;
}

Caching variations of a page based upon browser type:

Page Directive Approach

<%@ OutputCache Duration="3600" VaryByHeader="User-Agent" VaryByParam="None" %>

Programmatic Approach

Response.Cache.SetExpires(DateTime.Now.AddSeconds(3600));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.VaryByHeaders["User-Agent"] = true;

A High Performance Database Report

Assume your system resources are running low. You have determined that a majority of the problem is a database report that constantly runs with four different versions. You decide to implement server-side output caching so that each version of the report is only run once every hour.

STEP BY STEP

1.      Add a new Web Form to your Visual Studio C# application.

2.      Place a Label control (lblTimeLastGenerated), a DropDownList control (ddlCountry), a DataGrid control (dgReport), and a Button control (btnGetData) on the Web Form.

3.      Select the Items property on the ddlCountry and then click the ellipsis (…) button. Add the following properties in the Collection Editor Dialog: France, Brazil, Italy, and Germany.

4.      Now enter the following Page directive at the top of the Web Form’s HTML. This is the only line of code required for fragment caching.

<%@ OutputCache duration="3600" VaryByParam="ddlCountry" %>

Alternatively, use the HttpCachePolicy class in the code as follows:

Response.Cache.SetExpires(DateTime.Now.AddSeconds(3600));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetValidUntilExpires(true);
Response.Cache.VaryByParams["ddlCountry"] = true;

5.      Add the following code to the btnGetData button’s Click event handler in the code:

Listing 3 – Retrieving Database Reports

using System;
using System.Data.SqlClient;
 
private void Page_Load(object sender, EventArgs e)
{
   if (Page.IsPostBack == false)
         GetData();
}
 
private void btnGetData_Click(object sender, EventArgs e)
{
   GetData();
}
 
private void GetData()
{
   SqlConnection conn = new SqlConnection(
         "Data Source=(local); Initial Catalog=Northwind;" +
         " Integrated Security=SSPI");
 
   SqlCommand cmd = conn.CreateCommand();
   cmd.CommandType = CommandType.Text;
   cmd.CommandText = string.Format(
         "SELECT * FROM customers WHERE Country = '{0}'",
         ddlCountry.SelectedItem.Text);
   SqlDataAdapter da = new SqlDataAdapter();
   da.SelectCommand = cmd;
   DataSet ds = new DataSet();
   da.Fill(ds, "Customers");
   dgReport.DataSource = ds;
   dgReport.DataBind();
   lblTimeLastGenerated.Text = 
         string.Format("Last generated {0}, {1}",
         ddlCountry.SelectedItem.Text, DateTime.Now.ToString());
}

6.      Run the web page from several different computers and you will notice the same time reported for each country. This is because the data is being retrieved from server cache.

Caching at the client and Proxy

Client and proxy caches can only store a single version of the web page. Therefore you will need to remove the drop down list and button controls. Leaving these controls will allow the user to re-request possibly updated content from the server. However, when the client revisits the page he will view the previously cached data. This could cause a lot of confusion.

  • To specify output caching at the client use the following Page directive:
    <%@ OutputCache Duration="3600" Location="Client" VaryByParam="None" %>
  • To specify output caching at the client and proxy use the following Page directive:
     <%@ OutputCache Duration="3600" Location="Downstream" VaryByParam="None"%>

Revisiting a page cached at the client will display the original time that the client visited the page. Unlike server cache, visiting the page from another computer will display an entirely new time.

 


View Entire Article

User Comments

Title: Good one though problem with firefox   
Name: dotnetguts
Date: 2009-05-03 9:09:10 AM
Comment:
Thanks for good article, I have tried instruction mentioned in article, but it is still not working for firefox, any idea? to make it work.

DotNetGuts
http://dotnetguts.blogspot.com
Title: good one   
Name: vijay chand
Date: 2009-02-09 4:15:13 AM
Comment:
The above article has given me some knowledgeable thing
Title: REg. getting URLs of all visited Sites   
Name: Ad
Date: 2007-08-13 9:24:34 AM
Comment:
Hi

In the txt file, I only get the URL of this website, nothing more. Could you let me know what I m missing.
This is what I get -- 127.0.0.1;/CachingMadeSimple/OutputCachingClient.aspx;8/13/2007 6:46:57 PM

Also, could u explain the 2 minute time limit u hv put?
regards
Ad
Title: Software Enginner   
Name: Chintan Mehta
Date: 2007-07-02 9:55:09 AM
Comment:
This tutorial is very good but i want tutorial which describe actual in which scenario we have to use which type of caching. say in which condition fragment caching is usefull, in which condition data caching is usefull please describe with example if it is possible.

Thankyou.
Title: Software Engineer   
Name: Mudassar
Date: 2006-08-10 5:12:29 PM
Comment:
Excellent
Title: Great Article   
Name: Susan Dawson (Israel)
Date: 2006-04-08 9:17:06 PM
Comment:
This is one of many great articles you've written. I enjoy your easy to follow step by step articles. You are on my must read list.

Susan.
Title: Re: Images without roundtrip   
Name: Michael Libby
Date: 2006-01-31 10:12:32 AM
Comment:
Hi Fabio,
Regarding, "Copy your images to the ImagesCached directory and change all corresponding HTML references". This means that if your image directory changed then you must also change the source for your HTML Image Tag. For example, change the HTML IMG tag's src from src='NonCachedImgDir/MyImg.jpg' to src='CacheImgDir/MyImg.jpg'.
Title: images without roundtrip   
Name: Fabio Rauh
Date: 2006-01-31 7:21:57 AM
Comment:
Hi, I read your article and I´ve a doubt about how to cache images without roundtrip modification checking
I did not understand the step 7, what u mean "change" all corresponding html references. What do I have to do?
Thank you

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-26 7:20:00 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search