Developing a Hit Counter in ASP.NET
In this example, we will create a web page which will track and display the hit counts for the web site. ASP developers must be familiar with a similar technique used to track the hit counts in classic ASP web pages.
This web page can be easily re-used in the application, enabling you to provide the functionality in multiple web pages.
We track the hit count in a text file on the web server. We could have used an Application variable for the same job or persisted the value to a database.
To display the hit count, we read the current value from the text file, and increment it by one. We use GDI+ classes to create the image to display the counter value. Alternatively, this counter can be rendered using 10 pre-created images, displaying numbers from 0 to 9 and arranged to indicate the counter value. Creating graphic images on the fly to display the counter will allow us to extend our sample to customize the look and feel of the counter.
We will create a Visual C# web application and add a web page in the new project. This web page will hold the core functionality of managing the hit counter in the text file and returning a graphic image to render the counter value.
This web page does not contain any server controls. In the Page_Load event, add the following code.
The above code invokes methods to get the counter value and render the image for the counter value.
Let’s take a look at the code that fetches the counter value.
The above function just reads the value from a text file. If the text file does not exist, the default value of 0 is used. The counter is incremented and the new value is saved in the same text file for the next invocation. The hit counter value is then returned to the calling function.
The DrawCounter function uses GDI+ classes from the .Net Framework to render an image containing the counter value. Let’s take a look at this function.
Now we have a web page that draws a custom gif image containing the hit counter value. Let’s see how to use this functionality in our application web pages.
In the web page where you want to display the hit counter, you can add an image control. Set the ImageUrl property of the web page to point to the first web page. When the page is requested, the image will display the value of the hit counter.
Figure: The hit counter is displayed in our web form.
Complete code listing
– You can expand the sample by adding code to enhance/customize the hit counter image.
– You can make use of caching strategies and/or cookies to prevent the counter from incrementing on every page refresh.
Dipal Choksi is a Bachelor of Engineering (Computer Science). She has industry experience in team-effort projects and also as an individual contributor. She has worked on Visual Basic, Visual C++, Java, Directory Services, ASP projects