Caching Made Simple - A Practical Birdseye Overview
page 4 of 8
by Michael Libby
Average Rating: 
Views (Total / Last 10 Days): 140110/ 55

How to Use Data Caching

High Performance Web Site Statistics!

Let’s say you need to find out how much time users are spending on web pages, the common order in which web pages are navigated, and which web pages cause them to leave. Because your popular web site’s resources are running low, you decide to implement a combination of data caching and file storage to capture hit statistics while minimizing memory usage and hard disk activity.



1.      Open your Visual C# ASP.NET application’s Global.asax.cs file and add the following code:

Listing 1 – Capturing Web Site Statistics

using System;
using System.IO;
using System.Web;
using System.Web.Caching;
using System.Collections;

protected void Application_BeginRequest(Object sender, EventArgs e)
   // Ignore postbacks.
   if (System.Web.HttpContext.Current.Request.RequestType=="POST")
   // Get the cache object from application context.
   Cache cache = System.Web.HttpContext.Current.Cache;
   ArrayList HitArray = (ArrayList) cache["MyHitArray"];
   if (HitArray == null)
         // Create a two minute sliding expiration.
         TimeSpan ts = new TimeSpan(0,2,0);
         // Insert a HitArray object into data cache
         HitArray = new ArrayList();
         cache.Insert("MyHitArray", HitArray, null, 
               DateTime.MaxValue, ts, CacheItemPriority.Normal, 
               new CacheItemRemovedCallback(RemoveAndWriteCache));
   HitArray.Add(new Hit());

public void RemoveAndWriteCache(string key, object value, 
   CacheItemRemovedReason callbackreason) 
   // Note: State cannot be retrieved here; therefore the path is hard coded.
   // Workarounds could be to store the path within the cached object or 
   // preferably, to retrieve the path from the web.config file. 
   string filename = 
   // Create a thread safe TextWriter.
   StreamWriter s = new StreamWriter(filename, true);
   TextWriter writer = TextWriter.Synchronized(s);
   // Write each hit item out to file.
   foreach (Hit hit in (ArrayList) value)
               hit.IPAddr, hit.Url, hit.Time.ToString()));

2.      Add a new class to your application with the following syntax:

Listing 2 – Class Hit

public class Hit
   public string IPAddr;
   public string Url;
   public DateTime Time;
   public Hit()
         HttpRequest r = System.Web.HttpContext.Current.Request;
         IPAddr = r.UserHostAddress;
         Url = r.Url.AbsolutePath;
         Time = DateTime.Now;

3.      Visit web pages from several different computers.

4.      Wait two minutes so that the sliding expiration period ends causing the callback method, RemoveAndWriteCache, to be called.

5.      Open the Hits.txt file and you will see that the Hits ArrayList has been saved.

Run the application for a few days to collect enough information for Excel or another tool to analyze how much time is being spent on each page and which pages cause users to leave. You will need to sort by IP Address and time, calculate the time spent on each page, and so on, but you now have the beginnings of a high performance trend analysis tool.


View Entire Article

User Comments

Title: Good one though problem with firefox   
Name: dotnetguts
Date: 2009-05-03 9:09:10 AM
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.

Title: good one   
Name: vijay chand
Date: 2009-02-09 4:15:13 AM
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

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 --;/CachingMadeSimple/OutputCachingClient.aspx;8/13/2007 6:46:57 PM

Also, could u explain the 2 minute time limit u hv put?
Title: Software Enginner   
Name: Chintan Mehta
Date: 2007-07-02 9:55:09 AM
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.

Title: Software Engineer   
Name: Mudassar
Date: 2006-08-10 5:12:29 PM
Title: Great Article   
Name: Susan Dawson (Israel)
Date: 2006-04-08 9:17:06 PM
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.

Title: Re: Images without roundtrip   
Name: Michael Libby
Date: 2006-01-31 10:12:32 AM
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
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-2021  |  Page Processed at 2021-11-29 5:58:25 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search