Click here to Skip to main content
Click here to Skip to main content
Articles » Web Development » ASP.NET » General » Downloads
 
Add your own
alternative version

Page Tracking in ASP.NET

, 23 Jun 2004
This articles explains how to track visitors to your web site.
using System;
using System.Web;
using System.Text;
using System.Collections;
using System.Configuration;

using EAD.Controller;
using EAD.Constant;

namespace EAD.Utility
{
	public class PageTrackerUtil
	{
		private static string CreateTrackerPageListing(PageTracker tracker)
		{
			StringBuilder body = new StringBuilder();
			DateTime PreviousTime = DateTime.Now, FirstTime = DateTime.Now;
			TimeSpan ElapsedTime;
			bool first = true;

			body.Append("<br/><table bgcolor=\"#000099\" width=\"85%\" border=\"0\" align=\"center\" cellpadding=\"5\" cellspacing=\"1\">");

			if (tracker.Pages != null) 
			{
				ArrayList pages = tracker.Pages;

				string lastPage = string.Empty;

				body.Append("<tr><td class=\"TableLabel\">Visited Pages Count:</td><td class=\"Data\">" + pages.Count + "</td></tr>"  + Environment.NewLine);
				body.Append("<tr><td class=\"TableLabel\">Visited Pages</td><td class=\"TableLabel\">Elapsed Time</td></tr>"  + Environment.NewLine);
				foreach(PageData pti in pages)
				{
					if (first)
					{
						FirstTime = pti.Time;
						first = false;
					} 
					else
					{
						ElapsedTime = pti.Time.Subtract(PreviousTime);
						body.Append("<tr><td class=\"Data\">" + lastPage + "</td><td class=\"Data\">&nbsp;&nbsp;" + ElapsedTime.ToString().Substring(0, 8) + "</td></tr>"  + Environment.NewLine);
					}
					lastPage = pti.PageName;
					PreviousTime = pti.Time;
				}
				body.Append("<tr><td class=\"Data\">" + lastPage + "</td><td class=\"Data\">&nbsp;</td></tr>"  + Environment.NewLine);
				ElapsedTime = PreviousTime.Subtract(FirstTime);
				body.Append("<tr><td class=\"Data\">Total Time:</td><td class=\"Data\">&nbsp;&nbsp;<b>" + ElapsedTime.ToString().Substring(0, 8) + "</td></tr>"  + Environment.NewLine);
			} 
			else
			{	
				body.Append("<tr><td class=\"Data\">Visited Pages Count:</td><td class=\"Data\">0</td></tr>" + Environment.NewLine);
			}
			body.Append("</table>");
			return body.ToString();
		}

		private static string CreateTrackerMessageBody(PageTracker tracker)
		{
			StringBuilder body = new StringBuilder();
			body.Append(HTMLUtility.EMailMessageStyleSheet());
			body.Append("<table bgcolor=\"#000099\" width=\"85%\" border=\"0\" align=\"center\" cellpadding=\"5\" cellspacing=\"1\">");
			body.Append("<tr>");
			body.Append("<td colspan=\"2\" class=\"TableLabel\">Page Tracking Information</td>");
			body.Append("</tr>");

			string GeoByte = tracker.IPCity + " " + tracker.IPRegion + " " + tracker.IPCountry;

			body.Append("<tr><td class=\"Label\">UserHostAddress:</td><td class=\"Data\">" + tracker.SessionUserHostAddress);
			body.Append("&nbsp;" +  GeoByte + "&nbsp;</td></tr>" + Environment.NewLine);
			body.Append("<tr><td class=\"Label\">Date:</td><td class=\"Data\">" + DateTime.Now.ToString() + "</td></tr>" + Environment.NewLine);
			body.Append("<tr><td class=\"Label\">UserAgent:</td><td class=\"Data\">" + tracker.SessionUserAgent + "</td></tr>" + Environment.NewLine);
			body.Append("<tr><td class=\"Label\">Browser:</td><td class=\"Data\">" + tracker.Browser + "</td></tr>" + Environment.NewLine);
			body.Append("<tr><td class=\"Label\">Crawler:</td><td class=\"Data\">" + tracker.Crawler + "</td></tr>" + Environment.NewLine);


			string url = tracker.SessionURL;
			body.Append("<tr><td class=\"Label\">URL:</td><td class=\"Data\"><a href='" + url + "'>" + url +"</a></td></tr>" + Environment.NewLine);

			if (tracker.SessionReferrer != null)
			{
				url = tracker.SessionReferrer;
				body.Append("<tr><td class=\"Label\">Referer:</td><td class=\"Data\"><a href='" + url + "'>" + url + "</a></td></tr>" + Environment.NewLine);
			} 
			else
			{
				body.Append("<tr><td class=\"Label\">Referer:</td><td class=\"Data\">" + "</td></tr>" + Environment.NewLine);
			}

			body.Append("<tr><td class=\"Label\">Visits:</td><td class=\"Data\">" + tracker.VisitCount.ToString() + "</td></tr>" + Environment.NewLine);
			body.Append("<tr><td class=\"Label\">Orig Referer:</td><td class=\"Data\"><a href='" + tracker.OriginalReferrer + "'>" + tracker.OriginalReferrer + "</a></td></tr>" + Environment.NewLine);
			body.Append("<tr><td class=\"Label\">Orig URL:</td><td class=\"Data\"><a href='" + tracker.OriginalURL + "'>" + tracker.OriginalURL + "</a></td></tr>" + Environment.NewLine);
			body.Append("</table>");

			return body.ToString();
		}

		private static bool PageVisit(string relativeFilePath)
		{
			// For partial page tracking.
			bool visit = true;
			return visit;
		}

		private static bool ValidTracking(HttpContext ctx)
		{
			string ip = ctx.Request.UserHostAddress;
			string[] arrayString;
			string loginID = string.Empty;

			if (ctx.User.Identity.IsAuthenticated)
			{
				string name = ctx.User.Identity.Name;
				if (name != null && name.Length > 0)
				{
					string[] str = name.Split(',');
					if (str.Length > 0)
					{
						loginID = name.Split(',')[0];
					}
				} 
			}


			#region IncludeIPList. If this is empty then go to ExcludeIPList
			string includeIPList = ConfigurationSettings.AppSettings["IncludeIPList"];
			if (includeIPList == null || includeIPList.Length == 0) goto ExcludeIPListCheck;
			if (includeIPList.Length > 0)
			{
				arrayString = includeIPList.Split(',');
				foreach(string str in arrayString)
				{
					if (ip.StartsWith(str))
					{
						return true;
					}
				}
			}			
			#endregion

			#region ExcludeIPList. 
			ExcludeIPListCheck:
			string defaultExcludeList = ConfigurationSettings.AppSettings["ExcludeIPList"];
			if (defaultExcludeList == null) defaultExcludeList = "127.0.0.1,192.168,172.16,10.";
			if (defaultExcludeList.Length > 0)
			{
				arrayString = defaultExcludeList.Split(',');
				foreach(string str in arrayString)
				{
					if (ip.StartsWith(str))
					{
						return false;
					}
				}
			}
			#endregion

			// If there is no authenticated user then allow tracking to continue based upon IP criteria.
			if (loginID == string.Empty) return true;

			#region IncludeUserList
			string includeUserList = ConfigurationSettings.AppSettings["IncludeUserList"];
			if (includeUserList == null || includeUserList.Length == 0) goto ExcludeUserListCheck;
			if (includeUserList.Length > 0)
			{
				arrayString = includeUserList.Split(',');
				foreach(string str in arrayString)
				{
					if (loginID.Equals(str))
					{
						return true;
					}
				}
			}
			#endregion

			#region ExcludeIPList. 
			ExcludeUserListCheck:
			string excludeUserList = ConfigurationSettings.AppSettings["ExcludeUserList"];
			if (excludeUserList == null || excludeUserList.Length == 0) return true;
			if (excludeUserList.Length > 0)
			{
				arrayString = excludeUserList.Split(',');
				foreach(string str in arrayString)
				{
					if (loginID.Equals(str))
					{
						return false;
					}
				}
			}
			#endregion

			return true;
		}

		private static void UpdateSessionConst(string key, PageTracker tracker)
		{
			if (SessionConst.Session[key] == null)
			{
				SessionConst.Session.Add(key,tracker);
			} 
			else
			{
				SessionConst.Session.Remove(key);
				SessionConst.Session.Add(key,tracker);
			}
		}
		public static void TrackSessionStart(HttpContext ctx)
		{
			string key = ctx.Session.SessionID;
			string siteTracking = ConfigurationSettings.AppSettings["SiteTracking"];
			string ip = ctx.Request.UserHostAddress.ToString();
			if (siteTracking == null || siteTracking.Length == 0) return;
			if (siteTracking.ToLower() != "none" && ValidTracking(ctx))
			{
				PageTracker tracker = new PageTracker(ctx);
				UpdateSessionConst(key,tracker);
				EADUtility.SendMail(tracker.SessionUserHostAddress,CreateTrackerMessageBody(tracker));
			}
		}
		public static void TrackSessionEnd(string key)
		{
			string siteTracking = ConfigurationSettings.AppSettings["SiteTracking"];
			if (siteTracking == null || siteTracking.Length == 0) return;
			if (siteTracking.ToLower() != "none")
			{
				if (SessionConst.Session[key] != null)
				{
					PageTracker tracker = (PageTracker) SessionConst.Session[key];
					SessionConst.Session.Remove(key);
					SessionConst.Page.Remove(key);
					if (tracker != null)
					{
						EADUtility.SendMail(tracker.SessionUserHostAddress+"-End",CreateTrackerMessageBody(tracker)+CreateTrackerPageListing(tracker));
					} 
				} 
			}
		}
		public static void TrackSessionPages(HttpContext ctx)
		{
			string siteTracking = ConfigurationSettings.AppSettings["SiteTracking"];
			if (siteTracking == null || siteTracking.Length == 0 || siteTracking.ToLower() == "none") return;
			if (ctx.Session == null) return;

			string key = ctx.Session.SessionID;
			siteTracking = siteTracking.ToLower();
			if (siteTracking == "full" || siteTracking == "partial")
			{
				if (SessionConst.Session[key] != null)
				{
					PageTracker tracker = (PageTracker) SessionConst.Session[key];
					if (tracker != null)
					{
						string relativeFilePath = ctx.Request.Url.AbsolutePath.Remove(0, ctx.Request.ApplicationPath.Length).ToLower();
						// Remove things after ? mark.
						int pos = relativeFilePath.IndexOf("?");
						if (pos > 0)
						{
							relativeFilePath = relativeFilePath.Substring(0,pos);
						}
						if (siteTracking == "full")
						{
							tracker.AddPage(relativeFilePath);
						} 
						else if (PageVisit(relativeFilePath))
						{
							tracker.AddPage(relativeFilePath);
						}
						UpdateSessionConst(key,tracker);
					}
				}
			} 
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

vikramk
Web Developer
United States United States
Vikram is an Enterprise Application Architect specializing in EAI, ETL, all relational databases and transforming legacy applications to Microsoft .Net environment. Vikram works for a consulting firm in Research Triangle Park, NC. Vikram has expertise in all relational databases, Cobol, mainframe, OO programming, C, Perl and Linux. C# is a newfound craze for Vikram.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141220.1 | Last Updated 24 Jun 2004
Article Copyright 2004 by vikramk
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid