Monday 10 December 2012

Unique visitor counter in asp.net


In global.asax file 


<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="HitCounterControl.ascx.cs" Inherits="Rr.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>





 void Session_Start(object sender, EventArgs e)
        {                    
         

//Get & increment visitor count
            int count = 0;
            DataSet tmpDs = new DataSet();
            HttpContext currentContext = HttpContext.Current;
            if (currentContext != null)
            {              
                try
                {
                    tmpDs.ReadXml(Server.MapPath("~/HitCounter.xml"));
                    int i = 0;
                    String ipAddress = currentContext.Request.UserHostAddress;
                    Session["ipAddress"] = ipAddress;
                    while (tmpDs.Tables[0].Rows[i]["ipAddress"].ToString() != null)
                    {
                        if (ipAddress == tmpDs.Tables[0].Rows[i]["ipAddress"].ToString())
                        {
                            count++;
                        }
                        i++;
                    }
                }
                catch (System.IO.FileNotFoundException)
                {
                    throw;
                }
                catch
                {
                    //no need to throw exception for this
                }
            }
            if (currentContext != null && count==0)
            {
                try
                {
                    Session["Start"] = DateTime.Now;
                    //UserVisitCount();
                    // DataSet tmpDs = new DataSet();
                    //read hit count
                    tmpDs.ReadXml(Server.MapPath("~/HitCounter.xml"));
                    tmpDs.Tables[0].Rows.Add(tmpDs.Tables[0].Rows.Count + 1, currentContext.Request.UserHostAddress, DateTime.Now.ToString(), currentContext.Session.SessionID);
                    tmpDs.WriteXml(Server.MapPath("~/HitCounter.xml"));
                    //set in Session                  
                }
                catch { }
            }


            Session["HitCount"] = tmpDs.Tables[0].Rows.Count;


}




In user control






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 RR
{
    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["HitCount"].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();
        }
    }
}

//Drag and drop this user control to required web page


No comments:

Post a Comment