Monday, December 20, 2010

ASP.net - Count Online Visitor

In this article i will show you how to count online visitor in you'r website.

Step 1
Create a web application.

Step 2
Add a Global.asax file in a web project.Right click on the web application from solution explorer and select Add New Item,select Global.asax file from  installed Visual Studio templates.  

Step 3
In the Application_Start subroutine, we have to set the user count to 0, when the server starts the application,it is look like this



 void Application_Start(object sender, EventArgs e) 
    {
        try
        {
            // Set user count to 0 when start the web application. 
            Application["OnlineUsersCount"] = 0; 
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }

    }

Step 4
In the Session_Start subroutine, we have to increament the OnlineUsers by 1,it is look like this

 void Session_Start(object sender, EventArgs e) 
    {
        try
        {
            Application.Lock();
            Application["OnlineUsersCount"] = Convert.ToInt64(Application["OnlineUsersCount"]) + 1; // Increment online users by 1
            Application.UnLock(); 
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }

    }

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

Step 5
we must decrement the number of Active Users on the basis of online sessions in the Session_End subroutine,it is look like this

void Session_End(object sender, EventArgs e) 
    {
        try
        {
            Application.Lock();
            Application["OnlineUsersCount"] = Convert.ToInt64(Application["OnlineUsersCount"]) - 1; // Decrement online users by 1
            Application.UnLock();  
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

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

Application.Lock() and Application.Unlock()
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 6
we need to enable sessionstate and configure its mode to InProc value in our web.config file,it is look like this


<system.web>
    <sessionState mode="InProc" cookieless="false" timeout="20"></sessionState>
</system.web>

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 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.

The default Timeout is 20 minutes, so you can change it depending on the needs of your particular application.

Step 7
Add the following code in .aspx page for display online user count,it is look like this

<div>
        <%
            
            long OnlineUserCount = Convert.ToInt64(Application["OnlineUsersCount"]);
            Response.Write("Online Visitor Count : " + OnlineUserCount);     
            
         %>
    </div>

Run the project.

Download
Download Source Code

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
    or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.

    ReplyDelete