Hi,

I want to keep track of the number of visitors to my site.

I tried the following code in the Global.asax class,

public static int count = 0; 
void Application_Start(object sender, EventArgs e) 
{
 Application["myCount"] = count; 
}
 void Session_Start(object sender, EventArgs e)
 {
 count = Convert.ToInt32(Application["myCount"]); Application["myCount"] = count + 1; 
}

I am retrieving the value in the aspx page as follows:

protected void Page_Load(object sender, EventArgs e) 
{
int a;
    a = Convert.ToInt32((Application["myCount"]));
    Label4.Text = Convert.ToString(a);
    if (a < 10)
        Label4.Text = "000" + Label4.Text ;
    else if(a<100)
        Label4.Text = "00" + Label4.Text;
    else if(a<1000)
        Label4.Text = "0" + Label4.Text;
}

The above coding works fine. It generates the Visitors properly but the problem is when I restart my system, the count variable again starts from 0 which logically wrong.

I want the value of count to be incremented by 1 from the last count value.

So can anyone tell me how to accomplish this task?

Please help me out! Thanks in advance!

Dani AI

Generated

your counter resets because both Application state and static fields live only in the ASP.NET worker process. Any app pool recycle (server restart, deploy, web.config change, idle timeout, memory pressure) wipes them. Also, incrementing in Session_Start counts sessions, not true unique visitors, and it will vary across a web farm. ’s Application.Lock() fixes races, but not durability.

Use a durable store and an atomic increment. A tiny SQL table works well and survives restarts and scale-out.

SQL (run once):

CREATE TABLE dbo.VisitorCounter (
  Id int PRIMARY KEY,
  Total bigint NOT NULL
);
INSERT INTO dbo.VisitorCounter (Id, Total) VALUES (1, 0);

C# (e.g., in Session_Start if you mean per-session visits, or on a page hit if you mean page views):

using (var conn = new SqlConnection(
    ConfigurationManager.ConnectionStrings["Default"].ConnectionString))
using (var cmd = new SqlCommand(@"
    UPDATE dbo.VisitorCounter WITH (ROWLOCK, UPDLOCK)
    SET Total = Total + 1
    OUTPUT inserted.Total
    WHERE Id = 1;", conn))
{
    conn.Open();
    var total = (long)cmd.ExecuteScalar(); // latest count, atomically updated
    Label4.Text = total.ToString("D4");    // zero-padded
}

Notes:

  • If you truly want unique visitors, set a long-lived cookie (e.g., visitor-id). Only call the increment when the cookie is missing; then write it. This avoids inflating counts from the same person.
  • Bots and prefetchers will skew numbers. For accurate reporting, analyze IIS logs or use analytics as suggested, and keep this DB counter only for a lightweight display.

Recommended Answers

All 5 Replies

You should do analysis on your log files to deteremine the number of visitors. Check out "smarter stats."

Most of the Paid domains give this for free in their Control Panels. or you can try this

protected void Page_Load(object sender, EventArgs e)
    {
        Application.Lock();
        if(Application["HitCount"]!=null)
         {
            Application["HitCount"]=(int)Application["HitCount"]+1;
         }
        else
         {
             Application["HitCount"] =1;
         }
         Application.UnLock();
        lblInfo.Text="The page has been accessed ("+Application["HitCount"].ToString()+") times";
    }

or this might Help

Kind Regards

Vuyiswa Maseko

commented: neat, i didn't know about that +17

when you restart your system at that time IIS get close.Because of that all the information of users stored is get vanished.you have to use lock for that purpose.

Thanks a lot Vuyiswa Maseko

hi dear
You can also store count in another variable and make check the variables by applying condition code "if".

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.