This article explains how to add a graphic visitor counter to your website by adding a simple ASPX webpage with few lines of programming. You'll no more be required to add a third party free graphic counter utilities for your ASP.NET web site.

There are many visitor counters available as free utilities on internet, which requires you to paste a small code snippet on your website. This will display a dynamically render a counter image on your site page, and on clicking them it will take you to the counters website. You'll probably be required to display a tiny link to their website from your web page. All these are bearable, or infact even you can turn off all these extras and have the counter image alone displayed on the page, but the time it takes to load the image would sometimes be more annoying.
Let us create a simple odometer styles visit counter here using System.Net.Drawing classes.
First you need to count the number of unique visits to the website. The browser sends request to the server everytime you open a page on your website or make a postback action. If you count every request, you cannot arrive at the correct number of unique visitors on the website.
You cannot consider counting sessions here - because a session would be having a shorter life time to keep your site secure. Whenever session starts, if you count your unique visitor, you'll end up in a bigger count. This will not help you know how many visitors have come across your website, but instead will show how intense your users are using your website.
The best way to track your visitors is to use a cookie, which holds a unique ID in its value and having a sliding expiration upto 3-6 hours.
Const VISITOR_COOKIE As String = "WEBVISITOR"
Public Function GetCounter() As Integer
Dim newVisitorId As String
If Request.Cookies(VISITOR_COOKIE) Is Nothing Then
newVisitorId = Guid.NewGuid.ToString
'Execute the SQL command to increment the counter value in the Database table
DB.ExecuteCommand("UPDATE webcounter SET VisitorCounter = VisitorCounter + 1")
Else
newVisitorId = Request.Cookies(VISITOR_COOKIE).Values("Id")
End If
Dim ckVisitor As New HttpCookie(VISITOR_COOKIE)
newVisitorId = newVisitorId
ckVisitor.Values.Add("Id", newVisitorId)
ckVisitor.Expires = Now.AddHours(6)
Response.Cookies.Add(ckVisitor)
'Execute the SQL command to retrieve the current value of the counter from your Database table
Dim counter As Integer = DB.ExecuteCommand("SELECT VisitorCounter FROM webcounter")
Return counter
End Function
The above code will increment your visit count, whenever there is no cookie by name "WEBVISITOR" along with the request to the website. The cookie used here is set to expire after 6 hours, which makes it invalid for any visit to the website after 6 continuous hours of inactivity to your website from any visitor's browser. Sliding Expiration, which means that the validity of the cookie is extended on every visit, and the ultimate expiry time of the cookie is calculated from the last visit done to the website.
Let us now make the page which will work as the image provider for your graphic visitor counter.
Step 1: You need to create a new ASPX page for this purpose. Let us name this ASPX page as VisitCounter.aspx
In the code view (VisitCounter.aspx.vb), paste the above code blocks to get the counter's current value.
The following namespaces need to be imported:
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Drawing.Imaging
In the Page Load event, you can have the code as follows:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Response.Clear()
Response.Cache.SetNoStore()
Response.ContentType = "image/jpeg"
Dim length As Integer = 6
Dim fontSize As Integer = 16
Dim letterWidth As Integer = 15
Dim letterHeight As Integer = 18
Dim letterOffsetX As Integer = 2
Dim backgroundColor As Color = Color.Black
Dim number As Integer = GetCounter()
Dim sNum As String = number.ToString.PadLeft(length, "0")
Dim bmp As New Bitmap(letterWidth * length + 2, letterHeight + 2)
Dim gr As Graphics = Graphics.FromImage(bmp)
gr.CompositingQuality = CompositingQuality.HighQuality
gr.PixelOffsetMode = PixelOffsetMode.HighQuality
gr.InterpolationMode = InterpolationMode.HighQualityBicubic
gr.SmoothingMode = SmoothingMode.HighQuality
Dim bgBrush As New SolidBrush(backgroundColor)
gr.FillRegion(bgBrush, New Region(New Rectangle(0, 0, bmp.Width, bmp.Height)))
Dim font As New Font("Arial", fontSize, FontStyle.Bold, GraphicsUnit.Pixel)
For i As Integer = 0 To length - 1
gr.DrawRectangle(Pens.LightGray, New Rectangle(i * letterWidth + 1, 1, letterWidth, letterHeight))
gr.DrawString(sNum.Chars(i).ToString, font, Brushes.White, i * letterWidth + letterOffsetX, 1)
Next
gr.DrawRectangle(Pens.Gray, New Rectangle(0, 0, letterWidth * length + 2, letterHeight + 2))
bmp.Save(Response.OutputStream, Imaging.ImageFormat.Jpeg)
Response.End()
End Sub
Explanation:
The Response buffer is cleared fully, and the new content is set with content type "image/jpeg"
Response.Clear()
Response.Cache.SetNoStore()
Response.ContentType = "image/jpeg"
The code block below set the various parameters of the visitor counter - length of counter value, font size, width and height of each letter block, X-Offset of letter within each block, as well as the background color. There are other parameters like border color, etc. which you can change on the rendering code below.
Dim length As Integer = 6
Dim fontSize As Integer = 16
Dim letterWidth As Integer = 15
Dim letterHeight As Integer = 18
Dim letterOffsetX As Integer = 2
Dim backgroundColor As Color = Color.Black
Initialize the graphic object, and set it's properties. I have set the properties to render a high quality image.
Dim bmp As New Bitmap(letterWidth * length + 2, letterHeight + 2)
Dim gr As Graphics = Graphics.FromImage(bmp)
gr.CompositingQuality = CompositingQuality.HighQuality
gr.PixelOffsetMode = PixelOffsetMode.HighQuality
gr.InterpolationMode = InterpolationMode.HighQualityBicubic
gr.SmoothingMode = SmoothingMode.HighQuality
Fill the graphic object with a solid color, which you have chosen as the background color, and draw each character in the Counter Value string padded with zeros on left to make the required length. For each number, I have drawn a border also by using DrawRectangle. Draw an overall border also.
Dim bgBrush As New SolidBrush(backgroundColor)
gr.FillRegion(bgBrush, New Region(New Rectangle(0, 0, bmp.Width, bmp.Height)))
Dim font As New Font("Arial", fontSize, FontStyle.Bold, GraphicsUnit.Pixel)
For i As Integer = 0 To length - 1
gr.DrawRectangle(Pens.LightGray, New Rectangle(i * letterWidth + 1, 1, letterWidth, letterHeight))
gr.DrawString(sNum.Chars(i).ToString, font, Brushes.White, i * letterWidth + letterOffsetX, 1)
Next
gr.DrawRectangle(Pens.Gray, New Rectangle(0, 0, letterWidth * length + 2, letterHeight + 2))
Finally, save the graphic to Response.OutputStream in JPEG format (you have used Content-Type as image/jpeg), and close the Response Stream using Response.End
bmp.Save(Response.OutputStream, Imaging.ImageFormat.Jpeg)
Response.End()
The rendering logic used above is just a sample, and you can use your programming and creativity to create different styles of counters.
Step 2: Display the Visitor Counter on a webpage.
Displaying the custom visitor counter on any page of your site is quite a simple job. You just need to add an IMG tag with SRC property set to locate the VisitCounter.aspx. For safety of maintaining relative URLs, you can always use asp:Image control using the following syntax:
<asp:Image runat="server" id="visitCounter" ImageUrl="~/VisitCounter.aspx" />
Download the source code for this article here.