Implementing a visitor counter
Asked Answered
P

4

6

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

Plumbism answered 21/3, 2009 at 9:45 Comment(2)
I've checked this out and was able to reference the System.Data.SQLClient namespace and used the classes to connect to a DB in the global.asax file. What errors are you experiencing?Andvari
I was adding the reference as using System.Data.SqlClient; in Global.asax and getting error. Now I have changed to <%@ Import Namespace="System.Data.SqlClient" %> in Global.asax and not geeting any error. How to implement a global variable accessible in ALL pages/forms?? Lalit Kumar BarikPlumbism
H
1

Google analytic script is exactly what you need. Because session, will opens for crawlers too.

Heavyhanded answered 21/3, 2009 at 12:11 Comment(1)
Another way is using IIS log files, exists a lot of tools that provides parsing of them.Heavyhanded
C
6

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.

Chorea answered 21/3, 2009 at 15:16 Comment(0)
V
3

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

Vernissage answered 21/3, 2009 at 10:6 Comment(2)
Thanks for your kind reply. I will use Google Analytics as suggested. But still I am interested in addinng my own style/version of Visitor Counter, atleast to learn and expand my knowledge. I want to know how to implement a public/common function and global variables in ASP.Net 2.0. L.K. BarikPlumbism
Gareth> If one uses Google Analytics, then how to display Visitor Count on your web page? OR Any other web visitor counter that i can use that does not put its own URL or adv inside it?Ariannaarianne
L
1

I can only second Gareth's suggestion to use an already available traffic analysis. If you don't like the idea of giving Google data on your website's traffic, you can also download the log files and analyze them with one of the many web server log file analysis tools available.

Lanner answered 21/3, 2009 at 11:44 Comment(1)
Adrian> If one uses Google Analytics, then how to display Visitor Count on your web page? OR Any other web visitor counter that i can use that does not put its own URL or adv inside it?Ariannaarianne
H
1

Google analytic script is exactly what you need. Because session, will opens for crawlers too.

Heavyhanded answered 21/3, 2009 at 12:11 Comment(1)
Another way is using IIS log files, exists a lot of tools that provides parsing of them.Heavyhanded

© 2022 - 2024 — McMap. All rights reserved.