codetoad.com
  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! || Forums || 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
Sponsored by: FindMyHosting - Web Hosting Search
Summary: How to Cache pages, parts of pages and data in ASP.Net.
Viewed: 14361 times Rating (78 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
x.Load(Server.MapPath("/Messages.xml"))
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 http://itzimran.cjb.net




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'


To post comments you need to become a member. If you are already a member, please log in .

 



RELATED ARTICLES
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.
Creating a Dynamic Reports using ASP and Excel
by Jeff Anderson
A simple way to generate Excel reports from a database using Excel.
Create an ASP SQL Stored Procedure
by Jeff Anderson
A beginners guide to setting up a stored procedure in SQL server and calling it from an ASP page.
ASP Shopping Cart
by CodeToad Plus!
Complete source code and demo database(Access, though SQL compatible) to an ASP database driven e-commerce shopping basket, taking the user through from product selection to checkout. Available to CodeToad Plus! Members
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.
Creating an SQL Trigger
by Jeff Anderson
A beginners guide to creating a Trigger in SQL Server
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.
ASP.NET Forum Source Code
by ITCN
Complete open source website Forum and Discussion Board programmed in Microsoft dot Net 1.1 Framework with Visual Basic.
The asp:listbox control
by David Sussman, et al
The next HTML server control that we'll look at, <asp:listbox>, is very much related to <asp:dropdownlist>.
Concatenate strings in sql
by Jeff Anderson
A brief introduction to concatenating strings in an sql query (using SQL server or access databases).








Recent Forum Threads
•  Re: User input. Command line application.
•  email in bulk
•  problem displaying
•  Re: dynamic crystal report generation
•  reading text files line by line
•  Re: crystal report in windows C#.NET
•  is null or not an object error
•  Need to control remote machine
•  Re: convert minutes into hours and minutes


Recent Articles
What is a pointer in C?
Multiple submit buttons with form validation
Understanding Hibernate ORM for Java/J2EE
HTTP screen-scraping and caching
a javascript calculator
A simple way to JTable
Java Native Interface (JNI)
Parsing Dynamic Layouts
MagicGrid
Caching With ASP.Net


© Copyright codetoad.com 2001-2006