SiteExperts.com Logo Home | Community | Developer's Paradise | Jobs
User Groups | Site Tools | Site Information | Search

Inside Technique : Creating Counters with ASP : A Simple Visitors Counter

We are going to start with a simple counter that counts the total number of visitors on the site. This is accomplished simply by incrementing a counter each time a new session is created:

sub application_onstart
  ' Initialize
  application("num_visitors") = 0
end sub

sub session_onstart
  ' Session Starts
  application.lock
  application("num_visitors") = application("num_visitors") + 1
  application.unlock
end sub

In addition to the session_onstart event, there is also a corresponding session_onend event. This event occurs whenever an active session expires. By taking advantage of the onend event, you can also create a counter with the number of active visitors on the site.

sub application_onstart
  ' Initialize
  application("num_active") = 0
end sub

sub session_onstart
  ' Session Starts
  application.lock
  application("num_active") = application("num_active") + 1
  application.unlock
end sub

sub session_onend
  ' Session expires
  application.lock
  application("num_active") = application("num_active") - 1
  application.unlock
end sub

This counter has a benefit in that it is only relevant when the server is running. However, our first counter that counts the total visitors has a problem. Every time the server starts, the counter is reset. To fix this, you should trap the application_onend event and write the final count to a file on disk. When the server loads, this count should be used to reinitialize the variable. We show you how on the next page.