Hit Counter for ASP.NET using C# VB.NET

This is a very simple hit counter / page counter to see how many people have visited a web page if you want to show it on a web page. This is a simple user control that is meant to be on one page (i.e., the home page).

The requirements for this are a user control and read/write access to an xml file. Below is the code for the user control counter.ascx

Markup Code:


<%@ Control Language="C#" AutoEventWireup="true" CodeFile="counter.ascx.cs" Inherits="counter" %>
<asp:Label ID="lblCounter" runat="server"></asp:Label>



Code for the code behind:

C#


        protected void Page_Load(object sender, EventArgs e)
        {
            this.countMe();

            DataSet tmpDs = new DataSet();
            tmpDs.ReadXml(Server.MapPath("~/counter.xml"));

            lblCounter.Text = tmpDs.Tables[0].Rows[0]["hits"].ToString();
        }

        private void countMe()
        {
            DataSet tmpDs = new DataSet();
            tmpDs.ReadXml(Server.MapPath("~/counter.xml"));

            int hits = Int32.Parse(tmpDs.Tables[0].Rows[0]["hits"].ToString());

            hits += 1;

            tmpDs.Tables[0].Rows[0]["hits"] = hits.ToString();

            tmpDs.WriteXml(Server.MapPath("~/counter.xml"));

        }



VB.NET



        Protected Sub Page_Load(sender As Object, e As EventArgs)
            Me.countMe()

            Dim tmpDs As New DataSet()
            tmpDs.ReadXml(Server.MapPath("~/counter.xml"))

            lblCounter.Text = tmpDs.Tables(0).Rows(0)("hits").ToString()
        End Sub

        Private Sub countMe()
            Dim tmpDs As New DataSet()
            tmpDs.ReadXml(Server.MapPath("~/counter.xml"))

            Dim hits As Integer = Int32.Parse(tmpDs.Tables(0).Rows(0)("hits").ToString())

            hits += 1

            tmpDs.Tables(0).Rows(0)("hits") = hits.ToString()

            tmpDs.WriteXml(Server.MapPath("~/counter.xml"))
        End Sub



Then you need to have an xml file in the root directory to make the code work as well. The XML file will look like this:


    <?xml version="1.0" encoding="utf-8" ?>
    <counter>
      <count>
         <hits>0</hits>
      </count>
   </counter>


This should do it for a simple asp.net hit counter. Not much but it's something simple and clean. I've seen others out there and didn't like them too much and plus all the free ones require some type of advertising to be associated with it. This concept is easy and you can format it however you want!

Happy Coding!
Happy Shoding!

Popular Posts