In this post, you will see how to get number of active visitor's online in asp.net web site. Whenever distinct visitor opens the web site in his browser, new session is created for him. Here, I have used global HttpApplicationState class instance. HttpApplicationState class used to manage and share multiple sessions with in an ASP.NET web site. Let's start.
Open Global.aspx file from your web Application project, if it file does not exists, right click on your web application in the Solution Explorer, and select Add New Item -> Global Application Class. Following is the script of Global Application Class.
C#
void Application_Start(object sender, EventArgs e)
{
Application["onlineUsers"] = 0;
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
Application.Lock();
Application["onlineUsers"] = (int)Application["onlineUsers"] + 1;
Application.UnLock();
}
void Session_End(object sender, EventArgs e)
{
Application.Lock();
Application["onlineUsers"] = (int)Application["onlineUsers"] - 1;
Application.UnLock();
}
VB.NET
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
Application("onlineUsers") =0
End Sub
Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs on application shutdown
End Sub
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when an unhandled error occurs
End Sub
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
Application.Lock()
Application("onlineUsers") = Application("onlineUsers") + 1
Application.UnLock()
End Sub
Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
Application.Lock()
Application("onlineUsers") = Application("onlineUsers") - 1
Application.UnLock()
End Sub
Following is the code of Default.aspx page.
C#
Online users: <%=Application["onlineUsers"].ToString()%>
VB.NET
Online users: <%=Application("onlineUsers")%>
Note: You must have to call Application.UnLock() after calling Application.Lock(). Application.Lock is used to prevent from override the variable at the same time.
If you have better solution, please comments here to share with us.
Output

Download


online Visitors csharp.zip (140.37 kb)
online Visitors VB.zip (139.63 kb)