Search Mallstuffs

Flag Counter
Spirituality, Knowledge and Entertainment




Latest Articles


Move to top
Visitors-Hits counter for your website
Posted By Sarin on May 09, 2012     RSS Feeds     Latest Hinduism news
1367 Views

If you have a live Web site on the internet, then you may be interested in knowing how many people are visiting your site. You can of course go a long way to achieve this by analyzing the log files of your Web server but that information is usually difficult to read. The log files contain information for each and every request a visitor has made to your site, including resources like images, Flash movies and so on. This makes it near impossible to extract information about individual users. It would be a lot easier if you could count the number of individual users that have visited you since you started your site. You may also want to see the number of users that are currently browsing your site.



This article will show you how to accomplish these two tasks in two ways:
  1)    storing the hit counters in Application variables in the Global class
        If the server is rebooted, or the webserver is stopped and restarted, your hit counter will be reset. Also, to start hit counting for the first time, you will need to have the webserver stopped and restarted
  2)     Storing hit counters counts in a database/ xml.  
        If you are not sure about the stability of your web server, you can go by this method. By writing the counters to a database or xml, you can maintain their value even when your server is rebooted, or the webserver is stopped and restarted

The code in this article uses Sessions in ASP.NET, so you'll need to have them enabled them on your server, by configuring the <sessionState> element in the Web.config file.  
You'll also need to have access to a file called Global.asax in the root of your site. If you run your own Web server, this is not a problem and you can simply create the file yourself. If you are using an ISP, you'll need to check with them if they support the use of the Global.asax file as, unfortunately, not all ISPs allow this.
So, let us add the following code to our global asax file
protected void Application_Start(object sender, EventArgs e)
         {
                // This variable Hits will store the # of visitors
            Application["TotalUsers"] = 0;
            Application["ActiveUsers"] = 0;
        }
  
          protected void Session_Start(object sender, EventArgs e)
         {
            //Lock the Application for concurrency issues
            Application.Lock();
            //Increment the counter
       Application["TotalUsers"] = int.Parse(Application["TotalUsers"].ToString()) + 1;
      Application["ActiveUsers"] = int.Parse(Application["ActiveUsers"].ToString()) + 1;
            // Unlock the Application
            Application.UnLock();
  
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(Server.MapPath("~/counter.xml"));
            XmlNodeList nodeList = xmlDoc.SelectNodes("/counter/count");
            TotalUsers = int.Parse(nodeList[0].ChildNodes[0].InnerText);
            TotalUsers += 1;
            // update Total Users
            nodeList[0].ChildNodes[0].InnerText = TotalUsers.ToString();
            // update Active Users
            nodeList[0].ChildNodes[1].InnerText = Application["ActiveUsers"].ToString();
            // Don't forget to save the file
            xmlDoc.Save(Server.MapPath("~/counter.xml"));
  
        }
        protected void Session_End(object sender, EventArgs e)
         {
            //Lock the Application for concurrency issues
            Application.Lock();
            //Increment the counter
       Application["ActiveUsers"] = int.Parse(Application["ActiveUsers"].ToString()) - 1;
            // Unlock the Application
            Application.UnLock();
  
       }
  
What this code is doing is when Application_OnStart fires (it fires whenever the first visitor comes to your page after the server has last been restarted), we set out counters to 0 and store the value in Application Variable.  
The next step is to add code to the Session_Start event. This event will fire once for each user when they request the first page in your Web application. Inside this event, the values of the two hit counters are increased; one for the total number of users and one for the current number of users. Once the values are increased, the value of totalNumberOfUsers will be written to the xml as well. Instead of writing into xml, you can write to database as well.

Just as with the Session_Start event, we will write some code for the Session_End event as well. However, instead of increasing the counters, we will decrease the counter for the current number of users only. This means that whenever a user Session times out (Default to 20 minutes after they requested their last page), the counter will be decreased, so it accurately holds the number of current users on your site.  
  
Making Your Counters Accessible by Other Pages
You can have access to application variables directly in your aspx page. For accessing hit counters for database or xml scenario used above, easiest way would be to create two public properties in global.asax file. Because the Global class is in many respects just an ordinary class, we can add public properties to it as shown below.


  private static int _totalUsers;

        public static int TotalUsers
         {
            get  return Global._totalUsers;
            set  Global._totalUsers = value;
        }
  
  
        private static int _activeUsers;
  
        public static int ActiveUsers
         {
            get  return Global._activeUsers;
            set  Global._activeUsers = value;
        }
If you see the code above, we have used these variables to store counters
  
With these two properties in place, your calling code is now able to access the values of your hit counters. For example, to retrieve the number of users browsing your site right now, you can use this code: Global.ActiveUsers  
  
Full code of aspx file is as shown below.
Response.Write("<br>Active Users using XML:" + Global.ActiveUsers);
Response.Write("<br>Total Users using XML:" + Global.TotalUsers);
  
Response.Write("<br>Active Users using Application Variable:" + Application["ActiveUsers"].ToString());
Response.Write("<br>Total Users using Application Variable:" + Application["TotalUsers"].ToString());
Below is the output obtained after creating three sessions? Before creating these three sessions, I have restarted my website. So, we see total Users as 8(since 5 sessions was created before restarting the website).

General Conceptions of Website Counter
A couple of years ago it was very fashionable to have a 'Hit Counter' on your website. It supposedly showed the whole world how many 'hits' you've received to date.  Today you run the risk of being labeled a newbie, or a hobby website owner if you have a hit counter on your website. The problem with hit counters is that
1.   Nobody is quite sure what these 'hits' are counting. As you will see, collecting detail about website statistics is not as straightforward as it sounds. A hit could be anything from a unique visitor to the fact that you've displayed 5 graphical elements on your site (in which case, 5 hits will be recorded!)

2.   Hit counters, unlike odometers, are very easy to manipulate. It is not unknown for a desperate webmaster or website owner to set the hit counter to start at a vastly inflated number. Hit counters can also easily be reset - again to any number that you feel like.

3. Even If you have a website with very low traffic, would you really want to proclaim that to the world? Especially if you are trying to promote your website for advertising purposes (let this be a warning to anyone wanting to advertise on a website - first do some investigation into how much traffic the website gets before spending out big money).
As I mentioned, collecting accurate traffic statistics is not straight forward. Different website statistics tools also have different ways of referring to the traffic.

If you want accurate and measurable result I would advise you get a free web analytics account, this is the professional way of monitoring web traffic
 Summary
This article demonstrated how to create a hit counter that keeps track of the current and total number of users to your site. It stores these counters in static variables in the Global class so they are available in each page in your Web site. It also stores the value for the total number of users in a xml database so its value won't be lost when the Web server restarts, either unexpectedly, or on purpose.  
By using an Xml/database, you have created a solution that can easily be scaled to lots of users. If you have a real busy Web site, you can change the code from this article so it uses a real Database Management System, like Microsoft SQL Server or Oracle. This method will serve thousands and thousands of users a day allowing for lots of concurrent users.

here


Share this to your friends. One of your friend is waiting for your share.

Related Articles
Visitors-Hits counter for your website
Why and how to create RSS feeds in C#
Simple silver light sample application
Easiest Way of logging in .Net

Post Comment




Software developer by profession,
Poet by hobby,
Blogger by Passion
Birth Place: Munger, Bihar
Residence: Mumbai, Maharashtra
Prof exp: 8 years

Read More about me

Read my daily what'sapp quotes
Most Viewed Articles

Latest Spiritual Videos


Latest Funny Videos

Latest News

Latest Social Post
Latest WhatsApp Quotes