-->

Count Number of Visitors in WebSite using ASP.Net and C#



Introduction

In this post, I explain how to count number of visitors in WebSite using ASP.Net and C#.
Hit counters have become an important part of every website. To keep track of the number of visitors in our website we use this. Follow the below steps and do yourself.



Steps :

Just follow the steps and get result easily.

Step-1 : Create New Project

Go to File > New > Project > Select asp.net web forms application > Entry Application Name > Click OK.

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create a table.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Add a Class to Save / Get data from database.

Go to Solution Explorer > Right Click on Project under solution explorer > Add > New item > Select Class under Code > Enter Name > Add.

public class HitCount
    {
        public void AddCount(HitCounter HC)
        {
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                DateTime today = DateTime.Now.Date;
                // This code is for check unique ip per day only
                var v = dc.HitCounters.Where(a => a.IPAddress.Equals(HC.IPAddress) && EntityFunctions.TruncateTime(a.CreateDate) == today).FirstOrDefault();
                if (v == null)
                {
                    dc.HitCounters.Add(HC);
                    dc.SaveChanges();
                }
            }

        }

        public object[] GetCount()
        {
            object[] o = new object[2];
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                DateTime today = DateTime.Now.Date;
                // get Today Hits
                o[0] = dc.HitCounters.Where(a => EntityFunctions.TruncateTime(a.CreateDate) == today).Count();
               
                // get all hits

                o[1] = dc.HitCounters.Count();
            }
            return o;
        }

    }

Step-6: Add a User Control.

Go to Solution Explorer > Right Click on Project under solution explorer > Add > New item > Select Web User Control under Web > Enter Name > Add.

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UCHitCounter.ascx.cs" Inherits="AppHitCounter.UCHitCounter" %>
<table>
    <tr>
        <td>Today Visit : </td>
        <td align="right">&nbsp;&nbsp;<asp:Label ID="lblTodayVisit" runat="server" /></td>
    </tr>
    <tr>
        <td>Total Visit : </td>
        <td align="right">&nbsp;&nbsp;<asp:Label ID="lblTotalVisit" runat="server" /></td>
    </tr>

</table>

Write the followings code in your page load event for fetch Data(Hit Counter) from Database.


protected void Page_Load(object sender, EventArgs e)
        {
            // Show Hits
            object[] o = new object[2];
            o = new HitCount().GetCount();
            lblTodayVisit.Text = o[0].ToString();
            lblTotalVisit.Text = o[1].ToString();

        }

Step-7: Write Code inside Session_Start Event of Global.asax For Add hits into database.

void Session_Start(object sender, EventArgs e)
        {
            // Save hits
            HitCount hc = new HitCount();
            hc.AddCount(new HitCounter { SLID=0, IPAddress= Request.UserHostAddress, CreateDate= DateTime.Now });
        }

Step-8: Add user control into master page.

1st Register UserControl in Master page with below code in the design page at top of the page before <html> tag.

<%@ Register src="UCHitCounter.ascx" tagname="UCHitCounter" tagprefix="uc1" %>

2nd add this Code to add usercontrol into your master page.


<uc1:UCHitCounter ID="UCHitCounter1" runat="server" />

Step-9: Run Application.

Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.