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

Introduction: In this article i am going to explain 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. We can say we are going to create Hit Counter application in asp.net using both C# and VB.Net language. 
In previous articles i explained How to Convert Rupees,Currency or Numbers to Words and Get age in years,months,days,hours and seconds from DOB and Get Title,Description and Keywords Meta tags from URL and How to increase session timeout period and How to remove sessions and Create and consume WCF Services and What is cookie? Advantages and disadvantages of cookies.
count number of time site visited and online users in asp.net


Implementation: First of all we need to add global.asax file.
  • So right Click on your website name from Solution explorer -> Add New Item -> 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:

void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        Application["SiteVisitedCounter"] = 0;
        //to check 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;
        //to check 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.
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer
        // or SQLServer, the event is not raised.
        Application.Lock();
        Application["OnlineUserCounter"] = Convert.ToInt32(Application["OnlineUserCounter"]) - 1;
        Application.UnLock();
    }
  • In the design page (default.aspx) design the page as:
HTML Source Code:

<div>
    <fieldset style ="width:220px;">
    <legend>Count site visited and Online users</legend>   
        <asp:Label ID="lblSiteVisited" runat="server" Text=""
            style="color: #FFFFFF; background-color: #3366FF"></asp:Label><br />
        <asp:Label ID="lblOnlineUsers" runat="server" Text=""
            style="color: #FFFFFF; background-color: #009933"></asp:Label><br />
       
        <asp:Button ID="btnClearSesson" runat="server" Text="Clear Session"
            onclick="btnClearSesson_Click" />
        </fieldset>
        </div>

C#.Net code
  • In the code behind file(default.aspx.cs) write the code as:

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

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

Description: Application_Start event fires only once when very first user visit the site but Session_Start event fires as many times as many users visits the site and when session expires then Session_End event fires.

Note: Session doesn't expire on closing the browser. It expires in two ways. Either on time out (by default 20 minutes but it can be increased or decreased) or forcefully (e.g. using Session.Abandon()). On different browser session is also different.

Note: I have added a button "Clear Session" in this example. Actually there is no need of this button when this example will be live on the server. But to test it on our local server we need it to abandon the session so that you can see the variation in users online on the site.

Testing On local server: When you first run this example you will get No. of times site visited=1 and No. of users online on the site=1. Copy the Url from the browser and paste on another browser e.g. first run the website on Google chrome and copy the url from it and then paste it on Mozilla Firefox/ Internet Explorer etc. Now you will see No. of times site visited=2 and No. of users online on the site=2. 
Now click on the Clear Session Button of your example opened in the Google chrome. And refresh the Mozilla Firefox/ Internet explorer. You will see No. of times site visited=2 and No. of users online on the site=1.  It means one user's session got expired.

VB.Net Code
  • Design the page same as described in the Source code section above but replace the line         <asp:Button ID="btnClearSesson" runat="server" Text="Clear Session"    onclick="btnClearSesson_Click" />
with
         <asp:Button ID="btnClearSesson" runat="server" Text="Clear Session" /> 
  • Then In the code behind file(default.aspx.vb) write the code as:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        lblSiteVisited.Text = "No of times site visited=" & Application("SiteVisitedCounter").ToString()
        lblOnlineUsers.Text = "No of users online on the site=" & Application("OnlineUserCounter").ToString()
    End Sub

Protected Sub btnClearSesson_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClearSesson.Click
        Session.Abandon()
    End Sub

Now over to you:
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates."
Previous
Next Post »

25 comments

Click here for comments
Around Betul
admin
October 22, 2013 ×

Very well explained. :)

Reply
avatar
October 22, 2013 ×

Thanks Ashok for appreciating my work...stay connected and keep reading for more useful updates like this..:)

Reply
avatar
Unknown
admin
November 14, 2013 ×

Good Work sir.I am fan of you. Thanks for your Articles. you are genius sir... :)

Reply
avatar
November 14, 2013 ×

thanks Faisal Hasan..;)

Reply
avatar
Anonymous
admin
November 20, 2013 ×

Thank You so much.

Reply
avatar
January 29, 2014 ×

Your welcome Ashu Joshi..stay connected and keep reading for more useful updates like this..:)

Reply
avatar
January 31, 2014 ×

In Default.aspx.cs what is the refference of Application

Reply
avatar
February 01, 2014 ×

Hi, What exactly you are asking? i am not getting..

Reply
avatar
Unknown
admin
February 24, 2014 ×

Im having a problem, object reference was not set to an instance of an object...
how to fix this?

Reply
avatar
February 24, 2014 ×

Hello arvin madalura..where exactly you are getting this error? i suggest you to recheck all of your code and if still you face the same error then let me know, i will help you sort out this issue..

Reply
avatar
Unknown
admin
February 25, 2014 ×

Is theres a code to put on web config? I copy all the code given here, im using c# and it seems like, It show nothing on my page,...

Reply
avatar
aisha
admin
March 20, 2014 ×

sir i am making a project on online store. i m facing problem to work on the "add to cart" and "order". not getting any idea to start. can u hlp me.

Reply
avatar
Anonymous
admin
January 07, 2015 ×

thank you and you added the point to try in a different browser its much usefuk

Reply
avatar
January 30, 2015 ×

Your welcome vishal..stay connected and keep reading..:)

Reply
avatar
Unknown
admin
November 05, 2015 ×

nice code and Explaination...thanks

Reply
avatar
November 20, 2015 ×

Thanks mahesh for your valuable comment..Stay connected and keep reading for more useful updates.

Reply
avatar
Anonymous
admin
November 23, 2015 ×

very nice article.

Reply
avatar
December 12, 2015 ×

Thanks for your valuable comment. Stay connected and keep reading for more useful updates..:)

Reply
avatar
Unknown
admin
December 31, 2015 ×

Very nice explanation,....it is very helpful me

Reply
avatar
Unknown
admin
January 16, 2016 ×

simple and nice code sir, ,please add many more topics,thank you soo much!.

Reply
avatar
February 08, 2016 ×

Thanks for you feedback..I am glad you liked my article..stay connected and keep reading...

Reply
avatar
Prince Efue
admin
March 08, 2016 ×

sir is it possible to count online visitors in an mvc 5 application..please i need to know so as to make a choice if to migrate to mvc or remain with web forms
thanks in advance

Reply
avatar

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..