Thursday, January 24, 2013

Display online users in in ASP.NET application

To display online users in ASP.NET application u need to add a Global.asax file. Global.ascx is the ASP.NET application file. It has some application level events raised by ASP.NET application. In the below code whenever a user log in to your application a count will increase in Application["CurrentUsers"] state. The count will decrease when he Log Out.
  1. void Application_Start(object sender, EventArgs e)
  2. {
  3. // Code that runs on application startup
  4. Application["CurrentUsers"] = 0;
  5. }
  6.  
  7. void Application_End(object sender, EventArgs e)
  8. {
  9. // Code that runs on application shutdown
  10. }
  11.  
  12. void Application_Error(object sender, EventArgs e)
  13. {
  14. // Code that runs when an unhandled error occurs
  15. }
  16.  
  17. void Session_Start(object sender, EventArgs e)
  18. {
  19. // Code that runs when a new session is started
  20. Application.Lock();
  21. Application["CurrentUsers"] = (int)Application["CurrentUsers"] + 1;
  22. Application.UnLock();
  23. }
  24.  
  25. void Session_End(object sender, EventArgs e)
  26. {
  27. // Code that runs when a session ends.
  28. // Note: The Session_End event is raised only when the sessionstate mode
  29. // is set to InProc in the Web.config file. If session mode is set to StateServer
  30. // or SQLServer, the event is not raised.
  31. Application.Lock();
  32.  
  33. if ((int)Application["CurrentUsers"] > 0)
  34. {
  35. Application["CurrentUsers"] = (int)Application["CurrentUsers"] - 1;
  36. }
  37.  
  38. Application.UnLock();
  39. }
Then in the Code behind add the below code
  1. Label1.Text = Convert.ToString(Application["CurrentUsers"]);

No comments:

Post a Comment