devxlogo

Track Your Site Statistics Using ASP.NET’s Site Counters Service

Track Your Site Statistics Using ASP.NET’s Site Counters Service

s a Web developer, tracking Web site traffic is just one of the many activities you need to do. You might want to know which pages are the most popular, and more importantly, you might need that data to bill your advertisers. In any case, you can get the site statistics from the Web server log file or you can contract the service to a third-party site that tracks the page usage.

But in ASP.NET 2.0, you can use the built-in Site Counters service to track clicks and views for your Web application. In this article, I will show you how to create a simple ASP.NET 2.0-based Web site and track page views and clicks easily using the Site Counters service.

Creating the Sample Application
The sample Web site I’ll create is very simple: It has a few hyperlink controls as well as an AdRotator control. An AdRotator control displays a banner ad randomly every time the page that hosts it is loaded. The set of advertisements banners is saved in an XML document. Figure 1 shows the layout of the default Web page for my Web application (default.aspx):

For each hyperlink control I have set its CountClicks property to True so that the Site Counters service can track the click of each hyperlink control (see Figure 2).


Figure 1. Populate the Web page with the various controls.
?
Figure 2. To enable tracking for the Hyperlink control, set the CountClicks property to True.

But that’s not the only property you need to be concerned about. You use the CounterGroup property to specify a name with which to group click-events for similar controls. For Hyperlink controls, the default CounterGroup name is “Hyperlink.” The CounterName property is used to identify each unique Hyperlink control. Finally, the RowsPerDay property specifies the number of rows the counter should register. For example, if I specify 1440 in the RowsPerDay, the Site Counters service will record the clicks every minute–a single day has 1440 minutes (24 hours * 60 minutes). Later on, you will see how this is represented in the database.

Here is the source view for the four Hyperlink controls:

<asp:HyperLink ID="HyperLink1" Runat="server"     NavigateUrl="~/Books.aspx"     CountClicks="True"     CounterName="Books"      RowsPerDay="1440">[Books]asp:HyperLink><asp:HyperLink ID="HyperLink2" Runat="server"      NavigateUrl="~/Apparel.aspx"      CountClicks="True"     CounterName="Apparel"      RowsPerDay="1440">[Apparel & Accessories]asp:HyperLink><asp:HyperLink ID="HyperLink3" Runat="server"      NavigateUrl="~/Electronics.aspx"      CountClicks="True"     CounterName="Electronics"      RowsPerDay="1440">[Electronics]asp: HyperLink><asp:HyperLink ID="HyperLink4" Runat="server"      NavigateUrl="~/DVD.aspx"      CountClicks="True"     CounterName="DVD"     RowsPerDay="1440">[DVD]asp:HyperLink>

Note that the CounterGroup property is not present in the source view of the Hyperlink control. This is because I used the default value of “HyperLink.” If you use a non-default value, the property shows up in the source view.

To make the sample app functional, you need to add four new Web pages to your project–Books.aspx, Apparel.aspx, Electronics.aspx, and DVD.aspx. These will serve the purpose of legitimizing the Hyperlink controls in your application.

Tracking Ad Clicks with AdRotator

Figure 3. The images used by the AdRotator control are stored in a new Images folder.

Next you need to manipulate the AdRotator control. The AdRotator control displays advertisements randomly based on an XML file you specify. The XML file contains a list of images and links for various advertisements. Set the AdvertisementFile property of the AdRotator control to ‘~/advertisements.xml‘ and the CountClicks property to True. Leave the RowsPerDay property as -1 (default). A value of -1 will use a single row per day to store the click counts.

<asp:AdRotatorID="AdRotator1" Runat="server"      AdvertisementFile="~/advertisements.xml"      CountClicks="True" />

Here is my advertisements.xml file:

xmlversion="1.0" encoding="utf-8" ?><Advertisements>  <Ad>    <ImageUrl>~/images/twintower.jpgImageUrl>    <NavigateUrl>http://www.amazon.com/exec/obidos/ASIN/B0002JUXE2    NavigateUrl>    <AlternateText>Twin TowersAlternateText>    <CounterGroup>BannerAdvertisementCounterGroup>    <CounterName>TwinTowerCounterName>  Ad>  <Ad>    <ImageUrl>~/images/nationalgeographic.jpgImageUrl>    <NavigateUrl>http://www.amazon.com/exec/obidos/ASIN/B0002CHIME    NavigateUrl>    <AlternateText>National Geographic - Roar: Lions of the Kalahari    AlternateText>    <CounterGroup>BannerAdvertisementCounterGroup>    <CounterName>NationalGeographicCounterName>  Ad>Advertisements>

I have stored the images that the AdRotator control will use in the sample application in a folder named Images. (You can add a new folder to your project by right-clicking on the project name in Solution Explorer and then selecting New Folder from the context menu). Figure 3 shows the Solution Explorer and the images I’ve used for this example.

When the default.aspx page is loaded in a Web browser, you should see something similar to Figure 4.


Figure 4. The Hyperlink and AdRotator controls are in use.
?
Figure 5. The ASPNetDB.mdb file is an Access database file located under the Data folder.

Try clicking on the various Hyperlink controls as well as the AdRotator control. To see the different advertisements on the AdRotator control, refresh the page a few times.

After a while, stop your project and examine your Solution Explorer (see Figure 5). Refresh the Data folder (right-click on it and select Refresh Folder). You should see an Access database named ASPNetDB.mdb file located within this folder. By default, in Visual Studio Beta 1, the default Site Counters Provider uses an Access database to store the site statistics. You can change the provider to use a SQL Server via the Web.config file.

Figure 6. Examining the aspnet_SiteCounters table.

Double-click on the ASPNetDB.mdb file to open it (see Figure 6). The aspnet_SiteCounters table will display. If you look at the table carefully, you will notice that the first two rows represent the clicks made by the Books Hyperlink control in the first two minute-intervals (3:59 PM to 4:00 PM and 4:00 PM to 4:01 PM). This corresponds to the value of 1440 set in the RowsPerDay property as each row represents a minute.

The last row records the click made by the AdRotator control. Because I used the default value of -1 for the RowsPerDay property, you will notice that under the StartTime and EndTime fields, only the date is recorded and not the time. In this case, a row represents a single day.

Note that the Site Counters service will only register a click when the AdRotator control is clicked. There are times where you might want to register a view every time the page containing the AdRotator control is refreshed. In this case, you need to set the CountViews property to True.

Controls Supporting the Site Counters Service
The controls listed in Table 1 support the Site Counters service:

Table 1. List of controls supporting the Site Counters service

Control

Description

AdRotator

Displays an advertisement banner on a Web page

Hyperlink

A control that displays a link to another Web page

Button

Displays a push button control on the Web page

ImageButton

A control that displays an image and responds to mouse clicks on the image

LinkButton

Displays a hyperlink style button control on a Web page

PhoneLink

Represents a link (designed for phone devices)

ImageMap

Displays a clickable image map

Even though the ImageButton control supports the Site Counters service, it does not work in Visual Studio 2005 Beta 1. I will take this opportunity to show you a workaround for this bug; the solution will illustrate not only how to make ImageButton work with the service but also show you how to use the SiteCounter class to manually record clicks for any control that isn’t supported.

In Figure 7 I’ve modified the default.aspx page to include four ImageButton controls that replace the four Hyperlink controls I used earlier.

Figure 7. Default.aspx now uses four ImageButton controls in place of the four Hyperlink controls.

The following is the source view of the ImageButton controls:

<asp:ImageButton ID="ImageButton1" Runat="server"     ImageUrl="~/Images/tab_books.gif"     PostBackUrl="~/redirect.aspx?URL=books.aspx"      CountClicks="True"      CounterName="Books"      RowsPerDay="1440" /><asp:ImageButton ID="ImageButton2" Runat="server"     ImageUrl="~/Images/tab_apparel.gif"     PostBackUrl="~/redirect.aspx?URL=apparel.aspx"     CountClicks="True"     CounterName="Apparel"     RowsPerDay="1440" />     <asp:ImageButton ID="ImageButton3" Runat="server"     ImageUrl="~/Images/tab_electronics.gif"     PostBackUrl="~/redirect.aspx?URL=electronics.aspx"     CountClicks="True"     CounterName="Electronics"     RowsPerDay="1440" />     <asp:ImageButton ID="ImageButton4" Runat="server"     ImageUrl="~/Images/tab_dvd.gif"     PostBackUrl="~/redirect.aspx?URL=dvd.aspx"     CountClicks="True"     CounterName="DVD"     RowsPerDay="1440" />

Notice that each control is linked to a redirect.aspx page via the PostBackUrl property. A query string is also passed to the redirect.aspx page. This query string contains the destination page for each ImageButton control.

Here is the redirect.aspx page (which I have added to my project):

Sub Page_Load(ByVal sender As Object, _              ByVal e As System.EventArgs) _              Handles Me.Load    Dim URL As String = Request.QueryString("URL")    If URL IsNot Nothing Then        SiteCounters.Write("Links (manual)", URL, _                           "Click", URL, True, _                            True, Nothing, 1)        SiteCounters.FlushAll()        Response.Redirect(URL)    End IfEnd Sub

In the Page_Load event of the redirect.aspx page, I extract the query string using the Request.QueryString method. Then, I write the Site Counter entries to the database using the Write method of the SiteCounters class. The Write method is overloaded and allows you to specify information such as Counter group, Counter name, Counter event, and Navigate URL.

I use the FlushAll method in the redirect.aspx page to write the Site Counter information immediately to the database. The Site Counter service normally caches the data before writing it to the database at regular intervals. After you’ve used the FlushAll method, redirect the user to the destination page by using the Response.Redirect method.

With that done, I can now track the clicks of the ImageButton controls.

Viewing Site Statistics
Apart from viewing the site statistics directly from the database, a much more practical approach would be to programmatically retrieve the values from the database. The Site Counters service supports several methods to allow you to retrieve site statistics from the database (see Figure 8).

To illustrate how to retrieve the site statistics, I have added a Button control and a GridView control to the page (see Figure 9).


Figure 8. Use the SiteCounters class to manually get site traffic statistics from the database.
?
Figure 9. Add a Button and a GridView control to the page.

In the code-behind of the Get Site Counter Stats button, code the following:

Sub btnGetStats_Click(ByVal sender As Object, _                      ByVal e As System.EventArgs)    Dim ds As DataSet    ds = SiteCounters.GetRows(DateTime.MinValue, _         DateTime.MaxValue, Nothing, Nothing)    GridView1.DataSource = ds    GridView1.DataBind()End Sub
Figure 10. The site statistics, culled from the Site Counters class, are shown in a GridView control.

The statistics retrieved are returned as a Dataset object, which is then bound to a GridView control (see Figure 10).

The Site Counters service has really simplified the tasks of tracking page usage. No longer do you need to write utilities to extract information from the log files; everything can be done automatically within ASP.NET. Best of all, the Site Counters service works natively with the many Web server controls, in particular the AdRotator control, which will support your efforts to make your site a commercial success.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist