I would like to trace user information who is visiting my website(regardless of log in or not) and store user information in DB or Text file however, I only want to create one file for one visit.
How can I approch this functionality.
1. Should I creat HttpModule or
2. Session Start in Global.ascx file
what is the best way to approcah ...
I just scracthed some code below.....
void Session_Start(object sender, EventArgs e)
{
try
{
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);
}
}
void Application_PreRequestHandlerExecute(Object sender, EventArgs e)
{
try
{
UserInfo uInfo = new UserInfo();
uInfo.SessionID = this.Session.SessionID;
if (HttpContext.Current.Cache[uInfo.CacheKey] != null)
{
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)
{
}
}
AND I tested in label
private void Page_Load(object sender, System.EventArgs e)
{
try
{
IDictionaryEnumerator CacheEnum =Cache.GetEnumerator();
StringBuilder sb = new StringBuilder();
int intCount=0;
while (CacheEnum.MoveNext())
{
UserInfo uInfoCacheItem = (UserInfo)CacheEnum.Entry.Value;
sb.Append("UserName : ");
sb.Append(uInfoCacheItem.UserName + "");
sb.Append("SessionID : ");
sb.Append(uInfoCacheItem.SessionID + "");
sb.Append("StartTime : ");
sb.Append(uInfoCacheItem.StartTime + "");
sb.Append("Duration: ");
sb.Append(uInfoCacheItem.Duration + "");
sb.Append("LastPageVisited: ");
sb.Append(uInfoCacheItem.LastPageVisited + "");
sb.Append("MachineName:");
sb.Append(uInfoCacheItem.MachineName + "");
Label1.Text = string.Format("{0}", sb.ToString());
intCount +=1;
}
}
catch(Exception ex)
{
}
}