AspNet4YouTop 10sDevelopers WorldForums
Home
About
ASPNet Books
ASPNet Sites
ASPNet Hosters
View Articles
Search Articles
Authors
View Forums
 
Quick Menus
HOME
About
AspNet4You Forums
Articles
Authors
Search
Articles Summary
Articles(RSSFeed)
AspNet Books
AspNet Sites
AspNet Hosters
 Top 10 ASP.NET Books 
Professional ASP.NET 1.1
Essential ASP.NET With Examples in C#
ASP.NET Unleashed
Programming Data Driven Web Applications with ASP.NET
Professional ASP.NET Web Services
Beginning ASP.NET 1.1 with Visual C# .NET 2003
Programming Microsoft ASP.NET
Beginning ASP.NET Databases Using VB.NET
ASP.NET Security
Developing Microsoft ASP.NET Server Controls and Components
More...
 Top 10 ASP.NET Hosters 
WebHost4Life
DiscountASP.NET
MaximumASP
Brinkster
ORCS Web
myhosting.com
ISQSolutions
ASPwebhosting.com, LLC
Active ISP
Aquest Hosting
More...
 Top 10 ASP.NET Sites 
Asp.Net
GotDotNet
4GuysFromRolla.com
123aspx.com
EggHeadCafe.com
CShrp.Net
.NET 247
DevelopersDex.com
Csharp-Corner.com
dotnetspider
More...
Search Articles
Google
ASPNET4YOU      
Category:   Search Type:   Match Type:  
Trace Asp.Net Application User Information
Author: Saha, ProdipPosted: 2/28/2005 10:50:20 PM

Trace Asp.Net Application User Information

Would not it be nice to see who is visiting your website, what pages are they visiting and for how long? Yes, it's possible to trace all those information. This article will show you how to accomplish it. Keep in mind none can guarantee 100% accuracy of the duration of the visit or how many visitors there are due to the fact that no one can predict the user's behavior. For an example, if a user x out of the IE, the application have to wait until the session is timed out to drop the visitor count.

Let's get to the code - where, what?

Add the following codes in Global.asax.cs file:

 
protected void Session_Start(Object sender, EventArgs e)
{
	try
	{
		//UserInfo is nothing but a wraper class
		//with some properties and methods. This class is defined at 
		//the bottom of this article.
		
		UserInfo uInfo=new UserInfo();
		uInfo.SessionID=this.Session.SessionID;
		uInfo.UserName=HttpContext.Current.User.Identity.Name;
		uInfo.StartTime=DateTime.Now.ToString();
		uInfo.MachineName=CallingMachineName;
		
		TimeSpan SessTimeOut=new TimeSpan(0,0,HttpContext.Current.Session.Timeout,0,0);

		HttpContext.Current.Cache.Insert(uInfo.CacheKey,uInfo,null,DateTime.MaxValue,SessTimeOut);
		
	}
	catch(Exception ex)
	{
		throw new Exception("Error in Session_Start function",ex);
	}
}

protected void Application_PreRequestHandlerExecute(Object sender, EventArgs e)
{
	
	//Every call to the asp.net application can be intercepted
	//through this event
	try
	{
		UserInfo uInfo=new UserInfo();
		uInfo.SessionID=this.Session.SessionID;
		
		if(HttpContext.Current.Cache[uInfo.CacheKey]!=null)
		{
			// Accessing the Cache Item extends the Sliding Expiration automatically.
			string sUrl=HttpContext.Current.Request.RawUrl;
			if(sUrl.LastIndexOf("/")!=0)
			{
				sUrl=sUrl.Substring(sUrl.LastIndexOf("/")+1);
			}
			((UserInfo) HttpContext.Current.Cache[uInfo.CacheKey]).LastPageVisited=sUrl;
		}
	}
	catch(Exception ex)
	{
		//do nothing
	}
}

private string CallingMachineName
{
	//This method works for Intranet application
	//and it is not tested for Internet application
	get
	{
		try
		{
			string sTemp="";
			string sAddr="";
		
			sAddr = HttpContext.Current.Request.UserHostAddress;
			IPHostEntry host = null;
			host=Dns.GetHostByAddress(sAddr);
			if ( host != null )
			{
				sTemp = host.HostName;

				string [] split = null;
				string delimStr = ".";
				char [] delimiter = delimStr.ToCharArray();

				split=sTemp.Split(delimiter);

				if (split.GetUpperBound(0)>0)
				{
					sTemp=split.GetValue(split.GetLowerBound(0)).ToString();
				}
				
			}
		
			return sTemp;
		}
		catch(Exception ex)
		{
			throw ex;
		}
	}
}
						

Let's see what's in the UserInfo class file (UserInfo.cs):

 

using System;
using System.Text;

namespace ASPNET4YOU.COM
{
	/// 
	/// Summary description for UserInfo.
	/// 
	public class UserInfo
	{
		#region Private Variables And Constants
		private string _UserName="";
		private string _StartTime="";
		private string _EndTime="";
		private string _SessionID="";
		private string _LastPageVisited="";
		private string _MachineName="";
		#endregion Private Variables And Constants

		#region Constructors
		public UserInfo()
		{
			//
			// TODO: Add constructor logic here
			//
		}
		#endregion Constructors

		#region Private Properties
		#endregion Private Properties

		#region Public Properties
		public string UserName
		{
			get
			{
				return _UserName;
			}
			set
			{
				_UserName=value;
			}
		}
		
		public string StartTime
		{
			get
			{
				return _StartTime;
			}
			set
			{
				_StartTime=value;
			}
		}

		public string Duration
		{
			get
			{
				if(_StartTime!="")
				{
					TimeSpan tsDuration=DateTime.Now.Subtract(DateTime.Parse(_StartTime));
					string sDuration=tsDuration.ToString();
					if(sDuration.IndexOf(".")>=0)
					{
						sDuration=sDuration.Substring(0,sDuration.IndexOf("."));
					}

					return sDuration;
				}
				else
				{
					return String.Empty;
				}
			}
			
		}

		public string SessionID
		{
			get
			{
				return _SessionID;
			}
			set
			{
				_SessionID=value;
			}
		}

		public string CacheKey
		{
			get
			{
				return _SessionID;
			}
			
		}
		
		public string LastPageVisited
		{
			get
			{
				return _LastPageVisited;
			}
			set
			{
				_LastPageVisited=value;
			}
		}

		public string MachineName
		{
			get
			{
				return _MachineName;
			}
			set
			{
				_MachineName=value;
			}
		}
		
		#endregion Public Properties

		#region Public Enums
		#endregion Public Enums

		#region Private Methods
		#endregion Private Methods

		#region Public Methods
		#endregion Public Methods
	}
}

						

Now that we have enough information to trace the visitors, we have to have some sort of web interface(web form) to show the information. Let's add a Web Form (TraceUsers.aspx) with a code behind file (TraceUsers.aspx.cs). You can, as an alternative, create a user control (ascx) page and use it anywhere in the application.

TraceUsers.aspx:

Add a HtmlTable server control inside th Form tag and name it tblUserInfo
You may add some script to refresh the page for every n seconds in the onload event of the page.

//JavaScripts to refresh every 30 seconds


var sMsg;
var limit="0:30"; //min:sec
var parselimit=limit.split(":");
parselimit=parselimit[0]*60+parselimit[1]*1;

function beginrefresh()
{
	if (parselimit==1)
	{
		window.location.reload();
	}
	else
	{ 
		parselimit-=1;
		curmin=Math.floor(parselimit/60);
		cursec=parselimit%60;
		if (curmin!=0)
		{
			sMsg="This page will refresh in " +curmin +" minutes and "+cursec +" seconds."
		}
		else
		{
			sMsg="This page will refresh in " +cursec +" seconds."
		}
		window.status=sMsg;
		setTimeout("beginrefresh()",1000);
	}
}

				

TraceUsers.aspx.cs:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Caching;

namespace ASPNET4YOU.COM
{
	/// 
	/// Summary description for TraceUsers.
	/// 
	public class TraceUsers : System.Web.UI.Page
	{
		protected System.Web.UI.WebControls.Label lblErrors;
		protected System.Web.UI.HtmlControls.HtmlTable tblUserInfo;
		
		private void Page_Load(object sender, System.EventArgs e)
		{
			
			try
			{
				HtmlTableRow tr;
				HtmlTableCell td;

				//Get the already defined table(server) control
				HtmlTable tblUserInfo=(HtmlTable)this.FindControl("tblUserInfo");
				tblUserInfo.Align = "center";
				tblUserInfo.Border = 2;
				tblUserInfo.BorderColor="Blue";
				tblUserInfo.BgColor="lemonchiffon";
				tblUserInfo.CellPadding = 5;
				
				tr = new HtmlTableRow();
				tr.BgColor="Blue";
				tr.Attributes.Add("style","COLOR:white;FONT-WEIGHT:bold");				
				td = new HtmlTableCell();
				td.InnerHtml = "User Name";
				tr.Cells.Add(td);
					
				td = new HtmlTableCell();
				td.InnerHtml = "Session ID";
				tr.Cells.Add(td);

				td = new HtmlTableCell();
				td.InnerHtml = "Start Time";
				tr.Cells.Add(td);

				td = new HtmlTableCell();
				td.InnerHtml = "Duration(hh:mm:ss)";
				tr.Cells.Add(td);

				td = new HtmlTableCell();
				td.InnerHtml = "Last Visited";
				tr.Cells.Add(td);

				td = new HtmlTableCell();
				td.InnerHtml = "Machine Name";
				tr.Cells.Add(td);
					
				tblUserInfo.Rows.Add(tr);

				IDictionaryEnumerator CacheEnum =Cache.GetEnumerator();

				int intCount=0;
				while (CacheEnum.MoveNext())
				{
					UserInfo uInfoCacheItem = (UserInfo)CacheEnum.Entry.Value;
					tr = new HtmlTableRow();
					if((intCount%2)==1)
					{
						tr.BgColor="LightCyan";
					}
					
					td = new HtmlTableCell();
					td.InnerHtml = uInfoCacheItem.UserName;
					tr.Cells.Add(td);
					
					td = new HtmlTableCell();
					td.InnerHtml = uInfoCacheItem.SessionID;
					tr.Cells.Add(td);

					td = new HtmlTableCell();
					td.InnerHtml = uInfoCacheItem.StartTime;
					tr.Cells.Add(td);

					td = new HtmlTableCell();
					td.InnerHtml = uInfoCacheItem.Duration;
					tr.Cells.Add(td);

					td = new HtmlTableCell();
					td.InnerHtml = uInfoCacheItem.LastPageVisited;
					tr.Cells.Add(td);

					td = new HtmlTableCell();
					td.InnerHtml = uInfoCacheItem.MachineName;
					tr.Cells.Add(td);
					
					tblUserInfo.Rows.Add(tr);
					intCount +=1;
				}

			
			}
			catch(Exception ex)
			{
				//TODO:
			}


		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// 
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// 
		private void InitializeComponent()
		{    
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

	}
}
					
				

Prodip K. Saha
The Architect of ASPNET4YOU.COM

Terms and Conditions