Building a Simple Page Counter in ASP.net« View all ASP.net articles
March 25, 2007
We can use the Application State to easily create a simple page counter. We use PageCounter to achieve this.
This is our web form.
<div>
This page has been requested
<asp:Label ID="myLabel" runat="server" /> times.
</div>
We place our code in the Page_Load event.
Protected Sub Page_Load(ByVal
sender As Object,
ByVal e As
System.EventArgs) Handles Me.Load
'initialize page counter
If Application("PageCounter")
Is Nothing
Then
Application("PageCounter")
= 1
Else
'Increment counter
Application("PageCounter")
+= 1
End If
'set the label's text to the Page Counter
myLabel.Text = Application("PageCounter")
End Sub
The only problem is if multiple users access the page at the exact same time. To get around this issue we use the Lock and Unlock methods as illustrated below.
Protected Sub Page_Load(ByVal
sender As Object,
ByVal e As
System.EventArgs) Handles Me.Load
'initialize page counter
If Application("PageCounter")
Is Nothing
Then
Application("PageCounter")
= 1
Else
'lock the Application object
Application.Lock()
'Increment counter
Application("PageCounter")
+= 1
'unlock the Application object
Application.UnLock()
End If
'set the label's text to the Page Counter
myLabel.Text = Application("PageCounter")
End Sub
|