Tracking Sessions In ASP.Net

First, in the Application_OnStart sub, we basically set the user count to 0, when the server starts

			
                               Sub Application_OnStart (Sender as Object, E as EventArgs)
                                    /* Set our user count to 0 when we start the server */
                                    Application('ActiveUsers') = 0
                                End Sub
                           
		


Next, in the Session_OnStart subroutine, there are several things happening:

			
                                Sub Session_OnStart (Sender as Object, E as EventArgs)
                                    Session.Timeout = 10
                                    Session('Start') = Now
                                    Application.Lock
                                    Application('ActiveUsers') = Cint(Application('ActiveUsers')) + 1
                                    Application.UnLock
                                End Sub
                           
		


The first thing is the Timeout - you don't need to put anything here, but, the default Timeout is 20 minutes, so you can change or add it, depending on the needs of your particular application.

To set the session start time, we add (Session("Start") = Now). Basically, when the user hits the site and opens a web page (asp.net), at the time he/she opens the page, the session starts. Next, we increase the active visitors count when we start the session (Application("ActiveUsers") = Cint(Application("ActiveUsers")) + 1 ). The Application lock & unlock adds more stability to the counting.

Next, we must decrement the number of online sessions in the Session_OnEnd subroutine:

			
                                Sub Session_OnEnd(Sender as Object, E as EventArgs)
                                    Application.Lock
                                    Application('ActiveUsers') = Cint(Application('ActiveUsers')) - 1
                                    Application.UnLock
                                End Sub
                           
		


As you can see, it's pretty much the same code as adding to the current session count - Except - we subtract one from the count, decreasing the active visitors count when the session ends.