ASP 101 - Active Server Pages 101 - Web01
The Place ASP Developers Go!



Windows Technology Windows Technology
15 Seconds
4GuysFromRolla.com
ASP 101
ASP Wire
VB Forums
VB Wire
WinDrivers.com
internet.commerce internet.commerce
Partners & Affiliates
ASP 101 is an
internet.com site
ASP 101 is an internet.com site
IT
Developer
Internet News
Small Business
Personal Technology

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

ASP 101 News Flash ASP 101 News Flash



 Top ASP 101 Stories Top ASP 101 Stories
What is Adovbs.inc and Why Do I Need It?
An Overview of ASP.NET
Connections, Commands, And Procedures

QUICK TIP:
Use Response.Write Instead of Building Strings
Show All Tips >>
ASP 101 RSS Feed ASP 101 Updates


Caching

by John Peterson

Introduction

I have no clue who first thought of it, but caching is a great idea. You just use a small amount of something fast to make something slow seem much faster then it really is! It's done by motherboards, hard drives, operating systems, and in some form or another by almost everything where speed is important. That's why it was so upsetting that classic ASP had so little support for caching. The web server would do some caching of scripts on it's own, but it was pretty rudimentary and you had very little say in it what got cached and for how long. There are some third party alternatives and some scripts to enable caching in ASP (see the related links below), but they all have their problems. ASP.NET fixes this by including some first-rate caching support built right into the platform.

The Types of Caching in ASP.NET

ASP.NET supports three types of caching:

  • Output Caching: Caches the output from an entire page and returns it for future requests instead of re-executing the requested page.
  • Fragment Caching: Caches just a part of a page which can then be reused even while other parts of the page are being dynamically generated.
  • Data Caching: Programmatically caches arbitrary objects for later reuse without re-incurring the overhead of creating them.

Which type of caching you decide to use obviously depends on your situation, but I'll briefly cover them all so you can make an informed decision.

Output Caching

Output caching is the simplest of the caching options offered by ASP.NET. It is useful when an entire page can be cached as a whole and is analogous to most of the caching solutions that were available under classic ASP. It takes a dynamically generated page and stores the HTML result right before it is sent to the client. Then it reuses this HTML for future requests bypassing the execution of the original code.

Telling ASP.NET to cache a page is extremely simple. You simply add the OutputCache directive to the page you wish to cache.

<%@ OutputCache Duration="30" VaryByParam="none" %>

The resulting caching is similar to the caching done by browsers and proxy servers, but does have one extremely important difference... you can tell a page which parameters to the page will have an effect on the output and the caching engine will cache separate versions based on the parameters you specify. This is done using the VaryByParam attribute of the OutputCache directive. The code listing below (a shortened version of output_vary.aspx from the zip file available at the end of this article) illustrates a very simple example of output caching.

<%@ Page Language="VB" %>
<%@ OutputCache Duration="30" VaryByParam="test" %>
<html>
<body bgcolor="#FFFFFF">
<p>
This page was generated at: <strong><%= Now() %></strong>
</p>
</body>
</html>

This piece of code will cache the result for 30 seconds. During that time, responses for all requests for the page will be served from the cache. It also specifies that the caching should vary by the parameter "test". As such, the page will cache a different version for each value of "test" that it is passed and will return the appropriate version based on the value of "test" in the incoming requests.

Fragment Caching

Sometimes it's not possible to cache an entire page. For example, many shopping sites like to greet their users by name. It wouldn't look very good if you went to a site and instead of using your name to greet you it used mine! In the past this often meant that caching wasn't a viable option for these pages. ASP.NET handles this by what they call fragment caching.

Honestly, I find this a little misleading... while you can technically cache part of a page, in order to do so you need to make the section to be cached into a user control and set the OutputCache directive in the new user control. Then you use this control from your dynamic page. The solution works well, but in my mind I think of it as caching a separate mini-page and not really a fragment of a page. I guess it's just semantics, but it is a separate file so it can be a little bit of work to implement.

The caching part is very similar to the code above. Aside from making the section a user control and then using the user control (which we covered in our User Controls lesson) it's pretty boring. There's a sample in the zip file, but I'm not including the code here.

Data Caching

This is the most powerful of the caching options available in ASP.NET. Using data caching you can programmatically cache anything you want for as long as you want. The caching system exposes itself in a dictionary type format meaning items are stored in name/value pairs. You cache an item under a certain name and then when you request that name you get the item back. It's similar to an array or even a simple variable.

In addition to just placing an object into the cache you can set all sorts of properties. The object can be set to expire at a fixed time and date, after a period of inactivity, or when a file or other object in the cache is changed.

The main thing to watch out for with data caching is that items you place in the cache are not guaranteed to be there when you want them back. While it does add some work (you always have to check your object exists after you retrieve it), this scavenging really is a good thing. It gives the caching engine the flexibility to dispose of things that aren't being used or dump parts of the cache if the system starts running out of memory.

Here's a simple example of data caching. Once again it's simply a streamlined version of the script in the zip file.

<%@ Page Language="VB" %>
<script runat="server">
    Sub Page_Load(Sender As Object, E As EventArgs)
        Dim strTimestamp As String
        ' Retrieve our object
        strTimestamp = Cache.Get("SomeData")
        ' Check to see if we got our object back or not.
        ' If not, deal with it:
        If strTimestamp Is Nothing Then
            ' Assign a value to our object
            strTimestamp = Now()
            ' Insert into cache:
            Cache.Insert("SomeData", strTimestamp, Nothing, _
                DateTime.Now.AddMinutes(.5), TimeSpan.Zero)
        End If
        lblTimestamp.Text = strTimestamp
    End Sub
</script>
<html>
<body bgcolor="#FFFFFF">
<p>
This page was generated at: 
<strong><asp:label id="lblTimestamp" runat="server" /></strong>
</p>
</body>
</html>

Caching Rules... Get The Code

If you couldn't tell by now, I really like caching. It's an easy way to make your web pages and applications faster and it really doesn't cost you anything except for a little bit of time to figure out what to cache and for how long to cache it. It does use some memory, but with the price of memory these days, adding a little more (if needed) is a small price to pay for a faster web site.

As usual, the code from this lesson is all zipped up in a nice little file so you can download it and play with it on your own.

Related Information

ASP.NET Caching:

Classic ASP Caching:


Home |  News |  Samples |  Articles |  Lessons |  Resources |  Forum |  Links |  Search |  Feedback

Internet.com
The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers