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

Inside Technique : Creating Counters with ASP : Saving and Restoring Counters

To improve the counters value, they need to be able to persist themselves to disk. This makes sure your counter does not always restart at 0. We add persistence and reloading from disk with a simple modification to our original script.

sub application_onstart
  ' Initialize
  Dim objFSO, sPath
  Set objFSO = CreateObject("Scripting.FileSystemObject")
  sPath = Server.mapPath("counters.inc")
  if objFSO.fileExists(sPath) then
    Set objFile = objFSO.OpenTextFile(sPath)
    Application("num_visitors") = objFile.readLine
  else
    Set objFile = objFSO.CreateTextFile(sPath)
    objFile.write  "0" 
    application("num_visitors") = 0
  end if
  objFile.close()
end sub

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

Sub Application_OnEnd
  Dim objFSO, sPath
  Set objFSO = CreateObject("Scripting.FileSystemObject")
  sPath = Server.mapPath("counters.inc")
  Set objFile = objFSO.CreateTextFile(sPath)
  objFile.write application("num_visitors")
  objFile.close()
End Sub

At this point, you would assume that you have a reliable counter. However, there are very few circumstances where we have seen the application_onend event correctly fire. To work-around this, we also add a small check to the session_onstart event to write the value after every 50 or so visitors. For performance reasons we choose not to rewrite the variable on each visitors and choose to accept that the counter may lose up to 50 counts.

sub application_onstart
  ' Initialize
  Dim objFSO, sPath
  Set objFSO = CreateObject("Scripting.FileSystemObject")
  sPath = Server.mapPath("counters.inc")
  if objFSO.fileExists(sPath) then
    Set objFile = objFSO.OpenTextFile(sPath)
    Application("num_visitors") = objFile.readLine
  else
    Set objFile = objFSO.CreateTextFile(sPath)
    objFile.write  "0" 
    application("num_visitors") = 0
  end if
  objFile.close()
end sub

function SaveCounter(iCount)
  Dim objFSO, sPath
  Set objFSO = CreateObject("Scripting.FileSystemObject")
  sPath = Server.mapPath("counters.inc")
  Set objFile = objFSO.CreateTextFile(sPath)
  objFile.write iCount
  objFile.close()
end function

sub session_onstart
  ' Session Starts
  application.lock
  application("num_visitors") = application("num_visitors") + 1
  if application("num_visitors") mod 50=0 then
	SaveCounter(application("num_visitors"))
  end if
  application.unlock 
End Sub

Sub Application_OnEnd
  SaveCounter(application("num_visitors"))
End Sub

Next we revisit our original goal to create a browser counter.

Page 1:Creating Counters with ASP
Page 2:A Simple Visitors Counter
Page 3:Saving and Restoring Counters
Page 4:Advanced Browser-Based Counters