ASP Shopping CartForum & BBS
  - all for $20 from CodeToad Plus!
  Home || ASP | ASP.Net | C++/C# | DHTML | HTML | Java | Javascript | Perl | VB | XML || CodeToad Plus! || RAM 
Search Site:

Home » ASP » Article

Caching With ASP.Net

Article by: Imran Salahuddin Khan (1/11/2005)
Bookmark us now! Add to Favourites
Email a friend!Tell a friend
Summary: How to Cache pages, parts of pages and data in ASP.Net.
Viewed: 44382 times Rating (82 votes): 
 4.8 out of 5
 Rate this Article  Read Comments  Post Comments

Caching With ASP.Net

What is Caching?

"A process in which frequently accessed data is kept on hand, rather than constantly being retrieved from the place where it is stored."

In Classic ASP 3.0, we did not have any thing as powerful as ASP.Net Caching API through which we can cache whole pages (output caching), user controls (fragment caching) and perform data caching. In Classic ASP, we had cookies, sessions and application objects to store persistent information. Cookies collection in request and response object can store string information on the client computer but is limited to 4K. Sessions can store objects in the server memory and each session object in the server memory is associated with a specific browser. Storing large data in session object while thousands of users access the server at the same time can reduce the amount of available memory for coming users. Application objects behave like session objects; additionally the data stored in application object has application level scope and will be available to all users connected to the server. All 3 discussed objects can be used to cache information but have a lot of limitations and create many restrictions when developing applications based on cached data. Developers have to write a lot of code when caching data in any classic ASP object.

.Net Caching API comes with some new features:

1. A static object with a collection dedicated to storing and processing cache information (System.Web.Caching.Cache).
2. Caching dependent on any file (2.0 also supports SQL dependency)
3. Absolute and sliding expiration of cached data
4. Cached data priority to stay resident in memory and then retrieved with the callback method.

.Net Cache Techniques:

Page Output Cache:

You can cache the whole page along with itís data and business logic with the
Page Output Cache technique. Simply add the following directive in your .aspx file

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

Fragment Caching:

This directive specifies that the whole page will be cached for 60 seconds and no querystring parameter will affect the cached page. Providing querystring parameter name in varybyparam will expire the cache if the specified parameter changes its value. Suppose you have paged records and a querystring "PageNumber" is passed to the page to tell which page has to be shown. If you set VaryByParam to "none", you will see the same records on clicking next or the previous links. So the directive below can be used for this condition: <%@ OutputCache Duration="60" VaryByParam="PageNumber"%> So every time that the PageNumber parameter value changes, the cached data will expire.

Data Caching:

Another technique is used, when you donít want to cache the whole page but some part of page. If you have a page displaying categories in the left pane and other information in the rest of the page, fragment caching can be used to cache only the categories area. Fragment caching can be done by user controls. Create a user control (.ascx) for the categories and apply the output cache directive to the user control .ascx page. Finally, if you would like to cache some data only. Not any part of the page, or the whole page. Data caching can be used to achieve this goal. This kind of caching is done through programming and no directive is needed. You will have to import System.Web.Caching in .aspx code behind. Cache is a static/shared object and you donít need to create an instance for this object.

Cache ("key") = value Ďstore value or object
Var = Cache ("key") Ďretrieve value or object

For example: The code below is the "code - behind" class for the simple .aspx page. This page displays at two different times, one is cached and the other is not. Cached time is set at 30 seconds.

Imports System.Web.Caching
Public Class SimpleCache
Inherits System.Web.UI.Page
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Cache("CachedTime") Is Nothing Then
Cache.Insert("CachedTime", Now, Nothing, Now.AddSeconds(30), TimeSpan.Zero)
End If
Response.Write("Cached Time : " & Cache.Get("CachedTime") & "
Response.Write("Current Time : " & Now)
End Sub
End Class

In the code above, we used absolute expiration for cache and Now.AddSeconds(30) for 30 seconds expiration. We passed "Nothing" as cache dependency as we donít need it in this example. TimeSpan.Zero indicates that there is no relative expiration policy on this item. Cache Dependency plays a great role when you donít know the absolute expiration and want the cached page to expire when the file is modified.

For Example:

Imports System.Web.Caching
Public Class XmlDependentCache
Inherits System.Web.UI.Page
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Cache("NodeCache") Is Nothing Then
Dim x As New System.Xml.XmlDocument
Dim xNode As System.Xml.XmlNode
xNode = x.SelectSingleNode("Messages/MyMessage")
Cache.Insert("NodeCache", Now & ":" & xNode.InnerText, New CacheDependency(Server.MapPath("Messages.xml")))
End If
Response.Write("Cached Node Value : " & Cache.Get("NodeCache"))
End Sub
End Class

Messages.xml is a XML file, on which our cached item depends. As the last modified data is changed (you make some changes in file), the cache gets expired.

Article by Imran Khan

Useful Links

CodeToad Experts

Can't find the answer?
Our Site experts are answering questions for free in the CodeToad forums
Rate this article:     Poor Excellent
View highlighted Comments
User Comments on 'Caching With ASP.Net'
ASP FilesystemObject
by Jeff Anderson
An introduction to the Filesystemobject
ASP GetTempName
by Jeff Anderson
Use the GetTempName method to create a randomly generated temporary file on the server.
ASP Format Date and Time Script
by Jeff Anderson
An ASP script showing the variety of date and time formats possible using the FormatDateTime Function.
ASP OpenTextFile
by Jeff Anderson
An introduction to the OpenTextFile Method of the FileSystemObject
Email validation using Regular Expression
by Jeff Anderson
Using regular expression syntax is an exellent way to thoroughly validate an email. It's possible in ASP.
Add or Subtract Hours in SQL or ASP using DateAdd
by Jeff Anderson
A beginners guide to using the SQL DATEADD function to add or subtract hours. Particularly useful when setting the time displayed on the ASP page to a different time zone (eg when the server is in the US, and the site is for a UK audience).
The asp:radiobutton and asp:radiobuttonlist control
by David Sussman, et al
In HTML, radio buttons are used when we need to make multiple sets of choices available, but we want the user to select only one of them.
The asp:checkbox and asp:checkboxlist control
by David Sussman, et al
Checkboxes are similar to radio buttons, and in HTML, they were used to allow multiple choices from a group of buttons.
Concatenate strings in sql
by Jeff Anderson
A brief introduction to concatenating strings in an sql query (using SQL server or access databases).
ASP FileExists
by Jeff Anderson
An introduction to the FileExistsMethod of the FileSystemObject

Recent Forum Threads
• Run a program both on windows and linux
• VERO.SurfCAM.v2014
• Schlumberger.Petrel.V2013.2
• Petrel.V2013.2
• Altair.HyperWorks.v12
• VoluMill.v6.1
• VoluMill.NEXION.6
• VERO.SurfCAM.v2014
• Schlumberger.Petrel.V2013.2

Recent Articles
ASP GetTempName
Decode and Encode UTF-8
ASP GetFile
ASP FolderExists
ASP FileExists
ASP OpenTextFile
ASP FilesystemObject
ASP CreateFolder
ASP CreateTextFile
Javascript Get Selected Text

© Copyright 2001-2015