See also: ASP.Net - An XML Page Counter - VB.Net
A page counter is about as common a feature as you can get when it comes to the Internet and there are plenty of ways to add a page counter to your webpage and here's yet another! This method uses an XML document based on the name of the page being counter - which will allow you to use the same code with multiple pages in the same folder.
First of all, let's look at a simple XML document we can use to store the page counts to date. For the page counter, we will use a root node and a child node that will store the current value. Here's what the document will look like:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<page>
<views>1</views>
</page>
That's all there is to it - pretty simple. The very first time the page loads, we will create the document with an initial value of "1" and after that we will bump the counter and save the updated document.
We will be using the System.Xml and System.IO namespaces, which must be added with the 'Imports' statement at the top of the code:
Imports System.IO
Imports System.Xml
Next, we declare a public variable to store the count:
Public mintViews As Integer = 1
Since we don't want to count a re-load as a view, we will only update the counter when it's not a post back:
If Not Page.IsPostBack Then
UpdateCounter()
End If
The UpdateCounter routine uses the Page's Form name as the basis for the XML Counter:
string strCounterFilename
= HttpContext.Current.Server.MapPath(
"~/" + this.Form.Name + ".xml");
This file will not exist the very first time, so we need to check to see if the file exists. If it does, we will load it, and if not we will create it:
FileInfo fi = new FileInfo(strCounterFilename);
if (fi.Exists)
{
//Load the file counter file
doc.Load(strCounterFilename);
//Bump the counter
nodeViews = doc.SelectSingleNode("/page/views");
//Parse the inner text value
int.TryParse(nodeViews.InnerText, out mintViews);
//Bump the counter
mintViews++;
}
else
{
//Create a new document here
//Declaration
XmlDeclaration xmlHeader
= doc.CreateXmlDeclaration("1.0", "utf-8", "yes");
doc.AppendChild(xmlHeader);
//Add the root node
XmlNode nodeRoot = doc.CreateNode(XmlNodeType.Element, "page", null);
doc.AppendChild(nodeRoot);
//Add the Views tag
nodeViews = doc.CreateNode(XmlNodeType.Element, "views", null);
nodeRoot.AppendChild(nodeViews);
//Initialize the counter
mintViews = 1;
}
With the count updated, we update and save the document for next time:
//Save the document
nodeViews.InnerText = (mintViews).ToString();
doc.Save(strCounterFilename);
The counter is displayed on the ASP.Net page using the mintViews variable:
<p>
This page has been viewed <%=mintViews.ToString()%> times.
</p>