Friday, November 10, 2006

Counting Active Users in ASP

Although I have specifically addressed global.asa, I have written about it in the How to Filter out Bad Bots in ASP with Global.asa post. This method of keeping track of active users also uses the global.asa file along with an application variable. Put this in your global.asa:
<script language=vbScript runat=server>

sub session_onStart()
application.lock()
application("SCount") = application("SCount") + 1
application.unlock()
end sub

sub session_onEnd()
application.lock()
application("SCount") = application("SCount") - 1
application.unlock()
end sub

sub application_onStart()
' don't need a lock in onStart()
application("SCount") = 0
end sub
</script>
The, on any page you want to display the count, put
<%
Response.Write "Users Online: application("SCount")
%>
This method isn't 100% accurate and does have a few pitfalls:

It creates a "hotspot" during application.lock() that can cause delays when a new visitor arrives

You have no control over whether users launching new windows will trigger new sessions which will increment the count

You are constantly holding and modifying an application variable in memory, though you rarely use it

You need a modified copy of global.asa for each application, and have to aggregate different sites/applications separately

Nevertheless, for a quick and easy and mostly accurate way to count the number of active sessions, this will work.

No comments: