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.
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.
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:
<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."
25 comments
Click here for commentsVery well explained. :)
ReplyThanks Ashok for appreciating my work...stay connected and keep reading for more useful updates like this..:)
ReplyGood Work sir.I am fan of you. Thanks for your Articles. you are genius sir... :)
Replythanks Faisal Hasan..;)
ReplyThank You so much.
ReplyYour welcome...:)
Replythanx sir
ReplyYour welcome Ashu Joshi..stay connected and keep reading for more useful updates like this..:)
ReplyIn Default.aspx.cs what is the refference of Application
ReplyHi, What exactly you are asking? i am not getting..
ReplyIm having a problem, object reference was not set to an instance of an object...
Replyhow to fix this?
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..
ReplyIs 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,...
Replysir 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.
Replythank you and you added the point to try in a different browser its much usefuk
ReplyThanks
ReplyYour welcome vishal..stay connected and keep reading..:)
Replynice code and Explaination...thanks
ReplyThanks mahesh for your valuable comment..Stay connected and keep reading for more useful updates.
Replyvery nice article.
ReplyThanks for your valuable comment. Stay connected and keep reading for more useful updates..:)
ReplyVery nice explanation,....it is very helpful me
Replysimple and nice code sir, ,please add many more topics,thank you soo much!.
ReplyThanks for you feedback..I am glad you liked my article..stay connected and keep reading...
Replysir 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
Replythanks in advance
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..