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.
STEP BY STEP
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")
return;
// 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 =
@"C:\Inetpub\wwwroot\YourWebAppDir\hits.txt";
// 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)
writer.WriteLine(string.Format("{0};{1};{2}",
hit.IPAddr, hit.Url, hit.Time.ToString()));
writer.Close();
}
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.