Powered by Blogger.

Saturday, February 22, 2014

How to Count number of times website visited and online users in asp.net using C#.net?



In this article, we will discuss with example How to count the number of times the website is visited by the visitors/users and the users currently online on the website.

You can also check my previous post on:

- RegularExpressionValidator example in Asp.Net

- Export gridview data to excel sheet in Asp.net

- How to handle exception in sql server stored procedure?

First it's better to add a global.asax file. To add the global.asax file follow the below process

- Right Click on your website  -> Add NewItem -> Global Application Class. It will be added in the root directory of your website with the name "Global.asax".

- Open the global.aspx file and write the code on the Application_Start, Session_Start and the Session_End event as bellow:

void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        Application["SiteVisitedCounter"] = 0;
        //This will track how many users have currently opened our site write the following line
        Application["OnlineUserCounter"] = 0;
    }

 void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a new session is started
        Application.Lock();
        Application["SiteVisitedCounter"] = Convert.ToInt32(Application["SiteVisitedCounter"]) + 1;
        //This will track how many users have currently opened our site write the following line
        Application["OnlineUserCounter"] = Convert.ToInt32(Application["OnlineUserCounter"]) + 1;
        Application.UnLock();
    }

void Session_End(object sender, EventArgs e)
    {
        // Code that runs when a session ends.      
        Application.Lock();
        Application["OnlineUserCounter"] = Convert.ToInt32(Application["OnlineUserCounter"]) - 1;
        Application.UnLock();
    }

Put the controls like below in the design page (default.aspx).

<div>
    <fieldset style ="width:320px;">
    <legend>Count site visited </legend>
        <asp:Label ID="lblSiteVisited" runat="server" Text=""></asp:Label><br />
        <asp:Label ID="lblOnlineUsers" runat="server" Text=""></asp:Label><br />
               <asp:Button ID="btnClearSesson" runat="server" Text="Clear My Session"
            onclick="btnClearSesson_Click" />
        </fieldset>
        </div>

In the code behind file(default.aspx.cs) write the code as below:

protected void Page_Load(object sender, EventArgs e)
    {
        lblSiteVisited.Text = "No of times my site visited=" + Application["SiteVisitedCounter"].ToString();    
        lblOnlineUsers.Text = "No of users online on my site=" + Application["OnlineUserCounter"].ToString();
    }

    protected void btnClearSesson_Click(object sender, EventArgs e)
    {
        Session.Abandon();
    }





0 comments

Post a Comment