Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a visitor counter

I am a newbie and developing a website using ASP .Net 2.0 with C# 2005. I would like to add a facility to count the no. of visitors to my website. I have collected the basic informations to add this feature using Global.asax. I have made modifications to Web.config by adding the line "" under system.web section.

I am using a table to keep the count of visitors. But I don't know how to complete the task. My default Global.asax file came with different sections Application_Start, Application_End, Application_Error, Session_Start and Session_End. I have tried to extract the current value of the counter in the Application_Start section and store in a global variable. I would increment the counter in Session_Start and write the modified value to the table in Application_End.

I have tried to use public subroutines/functions. But where should I place those subroutines? I tried to add the subroutines in the Global.asax itself. But now I am getting errors, as I can not add reference to Data.SqlClient in Global.asax and I need references to SqlConnection, SqlCommand, SqlDataReader etc. to implement the features. Do I have to add Class files for each subroutines? Please guide me.

I would also like to implement tracking feature to my website and store the IP address, browser used, date and time of visit, screen resolution etc of my websites visitors. How can I do it?

Waiting for suggestions.

Lalit Kumar Barik

like image 891
LalitBarik Avatar asked Mar 21 '09 09:03

LalitBarik


People also ask

How does a visitor counter work?

When a person leaves the room or exit, the visitor is subtracted. Hence the total number of current visitors is displayed on OLED. The OLED Display also displays the number of visitors who visited the room and the number of visitors who exit. This is how an Arduino Visitor Counter with Light Control System works.

How can you implement visitor counter in Node JS?

For that case, we need to create the default record with the count of visitors equals 1(one). For other times just increment its value by one. We use the findOne() function of mongoose which takes a parameter as the searching condition. It returns the first record which matches our condition.


2 Answers

For a naive implementation, you can use a custom HttpModule. For each request to your application, you'd:

  1. Check if Request.Cookies includes a Tracking Cookie
  2. If the tracking cookie doesn't exist, this is probably a new visitor (or else, their cookie has expired -- see 4.)
  3. For a new visitor, log the visitor stats, then update the visitor count
  4. Add the tracking cookie to the response being sent back to the visitor. You'll want to set this cookie to have a rather long expiration period, so you don't get lots of "false-positives" with returning users whose cookies have expired.

Here's some skeleton code below (save as StatsCounter.cs):

using System;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Transactions;

namespace hitcounter
{
    public class StatsCounter : IHttpModule
    {
        // This is what we'll call our tracking cookie.
        // Alternatively, you could read this from your Web.config file:
        public const string TrackingCookieName = "__SITE__STATS";

        #region IHttpModule Members

        public void Dispose()
        { ;}

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
            context.PreSendRequestHeaders += new EventHandler(context_PreSendRequestHeaders);
        }

        void context_PreSendRequestHeaders(object sender, EventArgs e)
        {
            HttpApplication app = sender as HttpApplication;
            HttpResponse response = app.Response;
            if (response.Cookies[TrackingCookieName] == null)
            {
                HttpCookie trackingCookie = new HttpCookie(TrackingCookieName);
                trackingCookie.Expires = DateTime.Now.AddYears(1);  // make this cookie last a while
                trackingCookie.HttpOnly = true;
                trackingCookie.Path = "/";
                trackingCookie.Values["VisitorCount"] = GetVisitorCount().ToString();
                trackingCookie.Values["LastVisit"] = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss");

                response.Cookies.Add(trackingCookie);
            }
        }

        private long GetVisitorCount()
        {
            // Lookup visitor count and cache it, for improved performance.
            // Return Count (we're returning 0 here since this is just a stub):
            return 0;
        }

        void context_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = sender as HttpApplication;
            HttpRequest request = app.Request;

            // Check for tracking cookie:
            if (request.Cookies[TrackingCookieName] != null)
            {
                // Returning visitor...
            }
            else
            {
                // New visitor - record stats:
                string userAgent = request.ServerVariables["HTTP_USER_AGENT"];
                string ipAddress = request.ServerVariables["HTTP_REMOTE_IP"];
                string time = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss");
                // ...
                // Log visitor stats to database

                TransactionOptions opts = new TransactionOptions();
                opts.IsolationLevel = System.Transactions.IsolationLevel.Serializable;
                using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, opts))
                {
                    // Update visitor count.
                    // Invalidate cached visitor count.
                }
            }
        }

        #endregion
    }
}

Register this module by adding the following lines to your Web.config file:

<?xml version="1.0"?>
<configuration>
    ...
    <system.web>
        ...
        <httpModules>
          <add name="StatsCounter" type="<ApplicationAssembly>.StatsCounter" />
        </httpModules>
    </system.web>
</configuration>

(Replace with the name of your web application project, or remove it if you're using a Website project.

Hopefully, this'll be enough to get you started experimenting. As others have pointed out though, for an actual site, you're much better off using Google (or some other) analytics solution for this.

like image 168
elo80ka Avatar answered Oct 27 '22 20:10

elo80ka


Use Google Analytics. Don't try to reinvent the wheel unless a) the wheel doesn't do what you want or b) you're just trying to find out how the wheel works

like image 33
Gareth Avatar answered Oct 27 '22 19:10

Gareth