Unique Visitor Counter In Asp.Net

Introduction:

It is sometimes useful to display the number of visits a page on a Web site has experienced using a counter that's displayed as part of the page's content. While adding a counter to a page written in ASP or ASP.NET is relatively straight-forward, adding a counter to a plain HTML page (no scripting of any kind) is a little different.

This article describes a counter I created (see the following figure) using ASP.NET. . The code also maintains its own little "database" so that you don't have to FTP to your Web server to create a new counter. I use and designed this counter for my site listings and various other pages; so it is use a XMLfile to store the noumber of counts.

The Counter Lok like this image                      Visitor Count

000024


Creating The Counter:

Firstly you have to create a project in VS Studio And also you have to add a XML file and name it HitCounter to store the Hit counts, in the Global.asax file Write Down the following code:

Global.asax
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace HitCounter
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {
           //  Code that runs on application start
        }

        protected void Application_End(object sender, EventArgs e)
        {
            //  Code that runs on application shutdown

        }

        void Session_Start(object sender, EventArgs e)
        {
            //Get & increment visitor count
            UserVisitCount();

            DataSet tmpDs = new DataSet();
            try
            {
                tmpDs.ReadXml(Server.MapPath("~/App_Data/HitCounter.xml"));
            }
            catch (System.IO.FileNotFoundException)
            {
                throw;
            }
            catch
            {
                //no need to throw exception for this
            }

            //set in Session
            Session["hits"] = tmpDs.Tables[0].Rows[0]["hits"].ToString();
        }

        /// <summary>
        /// Increments visit count on every user session
        /// </summary>
        private void UserVisitCount()
        {
            try
            {
                DataSet tmpDs = new DataSet();
                //read hit count
                tmpDs.ReadXml(Server.MapPath("~/App_Data/HitCounter.xml"));
                int hits = Int32.Parse(tmpDs.Tables[0].Rows[0]["hits"].ToString());

                hits += 1;

                //write hit count
                tmpDs.Tables[0].Rows[0]["hits"] = hits.ToString();
                tmpDs.WriteXml(Server.MapPath("~/App_Data/HitCounter.xml"));
            }
            catch (System.IO.FileNotFoundException)
            {
                throw;
            }
            catch
            {
                //no need to throw for this
            }
        }
    }
}

After Writing these code you have to take now a user control to to render the Hit Counter.And give the name HitCounterControl.ascx. in the code behind file write the following code: To generate the table for the counter to show on the web form.

UserControl:


HitCounterControl.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="HitCounterControl.ascx.cs"
    Inherits="RebelsWeb.SiteControls.HitCounterControl" %>
<div style="padding-top: 15px; text-align: center">
    <span style="font-size:small">Visitor Count </span>
    <asp:Literal ID="ltlCounter" runat="server"></asp:Literal>
</div>

HitCounterControl.ascx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

namespace RebelsWeb.SiteControls
{
    public partial class HitCounterControl : System.Web.UI.UserControl
    {
        int totalDigits = 6;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ltlCounter.Text = FormatHTMLCounter(Session["hits"].ToString());
            }
        }

       /// <summary>
       /// Calculates and formats the vistor count number
       /// </summary>
       /// <param name="visitCount"></param>
       /// <returns></returns>
        private string FormatHTMLCounter(string visitCount)
        {
            int noOfDigits = visitCount.Length;
            int zeroesToPrefix = totalDigits - noOfDigits;
            StringBuilder strCounterHtml = new StringBuilder();
          
            strCounterHtml.Append(@"<table align=""center"" style=""width: 120px; background-color: Black; color: White; text-align: center; font-weight: bold;""><tr>");

            for (int i = 0; i < zeroesToPrefix; i++)
            {
                strCounterHtml.Append(@"<td style=""border:1px solid white; padding:2px"">");
                strCounterHtml.Append("0");
                strCounterHtml.Append("</td>");
            }

            char[] visitCountChar = visitCount.ToCharArray();
            for (int i = 0; i < visitCountChar.Length; i++)
            {
                strCounterHtml.Append(@"<td style=""border:1px solid white; padding:2px"">");
                strCounterHtml.Append(visitCountChar[i]);
                strCounterHtml.Append("</td>");
            }

            strCounterHtml.Append("</tr></table>");
            return strCounterHtml.ToString();
        }
    }
}
Now, After writing these code you can put this user control on web form to display the counter.


Summary

This article described how to create a fast page hit counter that's easy to use with plain HTML. The code uses ASP.NET and the C#.NET programming language to, automatically creating new counters, and preventing users from artificially inflating the value of the counter.

8 comments:

Saroj Kumar Kewat said...

This is very good blog to help for me.plz add in HitCounter.xml file:


0

Saroj Kumar Kewat said...

This is very good blog to help for me.plz add in HitCounter.xml file:


0

Sridhar G said...

hi, is it work in web applications?
i have create the application as web application ( not web Project), and please give me the format of xml file

M.Pradeep Rao said...
This comment has been removed by the author.
M.Pradeep Rao said...

hay please fin here xml file data
http://www.codeshode.com/2011/07/hit-counter-for-aspnet-using-c-vbnet.html

maggi said...

this code does not work on online server

maggi said...
This comment has been removed by the author.
vaitheswaran eswar said...

How can i call this user control in web form?