I’m facing with an old problem that it made me confuse very much. So I need your advice to make sure that I’ve been using the right way.
My demand is to count the number of visitor in my website, so I’ve coded in Global.asax file:
void Application_Start(object sender, EventArgs e)
{
// Get total visitor from database
long SiteHitCounter = 0;
int CurrentUsers = 0;
SiteHitCounter = MethodToGetTotalVisitorFromDatabase();
Application["SiteHitCounter"] = SiteHitCounter;
Application["CurrentUsers"] = CurrentUsers;
}
void Application_End(object sender, EventArgs e)
{
// Update total visitor to database when application shutdown
MethodToUpdateTotalVisitorToDatabase((long)Application["SiteHitCounter"]);
}
void Session_Start(object sender, EventArgs e)
{
// Increase total visitor and online user
Application["SiteHitCounter"] = (long)Application["SiteHitCounter"] + 1;
Application["CurrentUsers"] = (int)Application["CurrentUsers"] + 1;
}
void Session_End(object sender, EventArgs e)
{
// Decrease online user
Application["CurrentUsers"] = (int)Application["CurrentUsers"] - 1;
}
Then, I used variable Application[“SiteHitCounter”] and Application[CurrentUsers”] in another C# behind code file to show them on web page.
The problem I’m facing is that the website can’t show right total visitor number as in my database when I publish it to shared host.
I need your advice on this.
Thanks,
Tien
check the link..
Setting an Application(“Counter”) in the global.asax
You should lock the variable before update because Its shared now.
and if you want to make it fair apply some check to ip so that no one person can make multiple sessions.