Count user session

In Global.asax add the following code to keep track of user session


void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
Application.Add("userCount", 0);
}

void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
int userCount = int.Parse(Application.Get(“userCount”).ToString());
userCount++;
Application.Lock();
Application.Set(“userCount”, userCount);
Application.UnLock();
}

void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
int userCount = int.Parse(Application.Get(“userCount”).ToString());
userCount–;
Application.Lock();
Application.Set(“userCount”, userCount);
Application.UnLock();
}

The VB code to retrieve user session count is:


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim sIPAddress
sIPAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
If sIPAddress = "" Then
sIPAddress = Request.ServerVariables("REMOTE_ADDR")
End If

Label_userCount.Text = “There are ” & Application.Get(“userCount”) & ” user(s) online now”
Label_IP.Text = sIPAddress
End Sub

Advertisements

No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: