Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to count number of visitors for website in asp.net c#

Tags:

c#

asp.net

global

How do I count the number of visitors for website in asp.net c#?

I am using the code below:

In global.asax page:

<%@ Application Language="C#" %>

void Application_Start(object sender, EventArgs e)
{
    // Code that runs on application startup
    Application["NoOfVisitors"] = 0;
}

void Session_Start(object sender, EventArgs e)
{
    // Code that runs when a new session is started
    Application.Lock();
    Application["NoOfVisitors"] = (int)Application["NoOfVisitors"] + 1;
    Application.UnLock();
}

In .aspx page:

<asp:Label runat="server" ID="lbluser" />

In .aspx.cs:

protected void Page_Load(object sender, EventArgs e)
{
    lbluser.Text = Application["NoOfVisitors"].ToString();
}

The application counter is resetting to 0 every one hour ... Where have I erred in counting the number of users?

like image 418
Happy .NET Avatar asked Oct 04 '14 04:10

Happy .NET


1 Answers

Application State is volatile. Check the this MSDN articule:

When using application state, you must be aware of the following important considerations:

  • ...

  • Volatility Because application state is stored in server memory, it is lost whenever the application is stopped or restarted. For example, if the Web.config file is changed, the application is restarted and all application state is lost unless application state values have been written to a non-volatile storage medium such as a database.

So you should not use that for saving this kind of data that you want to persist over time. Because applications pools get reseted from time to time. And I suspect you don't want to reset your visitor count when that happens.

You'll need some kind of data store which can persist your data when you application is not running.

Here are some choices:

  • File (XML, JSON, plain text, etc.): sample xml code for visitors counter
  • Database (SQL Server, SQLite, etc.): sample database code for hit counter
like image 164
Mariano Desanze Avatar answered Oct 13 '22 06:10

Mariano Desanze