tags:

views:

634

answers:

2

Hi

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

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

<script runat="server">

  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;
  }

</script>

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!

A: 

If you want the count to keep incrementing over application restarts, you'll need to store the value somewhere - in a database or a file somewhere, and load that value up when the application starts.

Also, you can use the following to ensure your displayed count is always at least 4 characters:

int a;
a = Convert.ToInt32(Application["myCount"]);
Label4.Text = a.ToString("0000");

See Custom Numeric Format Strings for more info.


Edit to respond to comment

Personally, I'd recommend using a database over writing to the file system, for at least the following reasons:

  1. Depending on your host, setting up a database may well be a lot easier than enabling write access to your file system.
  2. Using a database will allow you to store it as an int rather than a string.
  3. Under heavy traffic, you'll have issues with multiple threads trying to open a text file for write access - which will cause a lock on the file, and cause a bottle neck you don't need.

Various resources will tell you how to connect to a database from your code, a good place to start would be this How To: Connect to SQL Server, and looking into the methods under "What are the alternatives" for details on how to query and update the database.

Zhaph - Ben Duguid
A: 

Usually you use other Tools for that Task (weblog analyser).

As you store your value in Memory (Application["myCount"]) this value will not survive a server restart. So you have to store it in a

  • database
  • plain textfile
  • whatever
Arthur
Ok Thanks for your reply.If you dont mind can you tell me how to do it? and whether storing it in a database or text file is advantageous?
Sheetal