Wednesday 21 September 2011

Getting number of active sessions (online users counter) with ASP.NET

All that have to be done is in global.asax file:
 Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
Application["OnlineUsers"] = 0
End Sub



Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
Application.Lock();
Application["OnlineUsers"] = CInt)Application["OnlineUsers"] + 1
  Application.UnLock();

End Sub
Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
Application.Lock()
Application(
"OnlineUsers") = CInt)Application["OnlineUsers"]- 1 
Application.UnLock();
End Sub

And to get the counter value in any form you want just call Response.Write(Application["OnlineUsers"]);
or Label1.Text = Application["OnlineUsers"].ToString(); whatever you feel comfortable.
It will show all open sessions.
Application.Lock() is used to lock down the application state values for editing only from one person at a time and Application.UnLock() is unlocking the state for edit from somebody else.

No comments:

Post a Comment