Saturday, April 3, 2010

How to show number of online users / visitors for ASP.NET website?

There are many ways to count number of active visitors on your ASP.NET website.
They differ in technique and accuracy.

here is the simplest approach that delivers acceptable accuracy when configured optimally:

Step 1:

- first we need to add these lines to our global.asax file
(if your website do not have it, create it by right-clicking on website in solution explorer,
and choosing Add New Item > Global Application Class option)

void Application_Start(object sender, EventArgs e)


// Code that runs on application startup

Application["OnlineUsers"] = 0;


void Session_Start(object sender, EventArgs e)


// Code that runs when a new session is started


Application["OnlineUsers"] = (int)Application["OnlineUsers"] + 1;



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.


Application["OnlineUsers"] = (int)Application["OnlineUsers"] - 1;



This will allow us that whenever some distant web visitor opens our website in his browser,
and new session is created for him, our "OnlineUsers" variable in the global HttpApplicationState class instance
is increased.

Also when user closes his browser or does not click on any links in our website, session expires,
and our "OnlineUsers" global variable is decreased.

To know more about ApplicationState and HttpApplicationState class visit this MSDN link:

NOTE: we are using Application.Lock and Application.Unlock methods to prevent multiple threads
from changing this variable at the same time.

By calling Application.Lock we are receiving exclusive right to change the values in Application state.
But we must not forget to call Application.Unlock() afterwards.

Step 2:
In order for this to work correctly we need to enable sessionstate and configure its mode to InProc value (in our web.config file):

In-process mode stores session state values and variables in memory on the local Web server.
It is the only mode that supports the Session_OnEnd event that we used previously.

Timeout value (in minutes, not in seconds) configures how long our sessions are kept 'alive' - in other words
here we set how long our users can be inactive before considered Offline.

In this example timeout is set to 20 minutes, so while our visitors click on some links in our website at least once
in a 20 minutes, they are considered online.
If they do not open any pages on our website longer than 20 minutes, they are considered Offline, and their session
is destroyed, so our online visitor counter is decreased by 1.
(You can experiment with lower or higher values of Timeout settings to see what is the best for your website).

Ok, so now we are done with configuration steps, let us see how to use this:

To show number of online visitors/users on your ASPX page you can use this code:

Visitors online: <%= Application["OnlineUsers"].ToString() %>
Next you could put this code snippet in you UserControl, or inside Asp.Net AJAX UpdatePanel control, and
use Timer to refresh it in regular intervals without refreshing the whole page, but that is another story

How to access Session values from my custom HttpHandler in ASP.NET?
If you try to create a custom HttpHandler in ASP.Net just by creating a custom class that implements only the IHttpHandler interface you will come across a strange limitation: your HttpHandler code wont be able to access the Session object, for example in the ProcessRequest method.

This is because in order to access the Session object (and its values) from your custom HttpHandler you need to implement another interface: IRequiresSessionState

(Don't worry, its just a marker interface and it does not enforce you to add any more methods to your class, it just 'tells' the ASP.NET runtime that you need to access the Session object in your code:

public class CaptchaImageGenerator : IHttpHandler, IRequiresSessionState


// your code that access the Session object comes here...


More info about the topic on this MSDN page: IHttpHandler Interface


No comments:

Post a Comment