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>    NavigateUrl>    <AlternateText>Twin TowersAlternateText>    <CounterGroup>BannerAdvertisementCounterGroup>    <CounterName>TwinTowerCounterName>  Ad>  <Ad>    <ImageUrl>~/images/nationalgeographic.jpgImageUrl>    <NavigateUrl>    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




Displays an advertisement banner on a Web page


A control that displays a link to another Web page


Displays a push button control on the Web page


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


Displays a hyperlink style button control on a Web page


Represents a link (designed for phone devices)


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.



Share the Post:
5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1

Copilot Revolution

Microsoft Copilot: A Suit of AI Features

Microsoft’s latest offering, Microsoft Copilot, aims to revolutionize the way we interact with technology. By integrating various AI capabilities, this all-in-one tool provides users with an improved experience that not

AI Girlfriend Craze

AI Girlfriend Craze Threatens Relationships

The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious repercussions for America’s future. A

AIOps Innovations

Senser is Changing AIOps

Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the root causes of service disruptions

Bebop Charging Stations

Check Out The New Bebob Battery Charging Stations

Bebob has introduced new 4- and 8-channel battery charging stations primarily aimed at rental companies, providing a convenient solution for clients with a large quantity of batteries. These wall-mountable and

Malyasian Networks

Malaysia’s Dual 5G Network Growth

On Wednesday, Malaysia’s Prime Minister Anwar Ibrahim announced the country’s plan to implement a dual 5G network strategy. This move is designed to achieve a more equitable incorporation of both

Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to Russia’s rapid utilization of airborne

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered around improving user experience, streamlining

Price Wars

Inside Hyundai and Kia’s Price Wars

South Korean automakers Hyundai and Kia are cutting the prices on a number of their electric vehicles (EVs) in response to growing price competition within the South Korean market. Many

Solar Frenzy Surprises

Solar Subsidy in Germany Causes Frenzy

In a shocking turn of events, the German national KfW bank was forced to discontinue its home solar power subsidy program for charging electric vehicles (EVs) after just one day,

Electric Spare

Electric Cars Ditch Spare Tires for Efficiency

Ira Newlander from West Los Angeles is thinking about trading in his old Ford Explorer for a contemporary hybrid or electric vehicle. However, he has observed that the majority of

Solar Geoengineering Impacts

Unraveling Solar Geoengineering’s Hidden Impacts

As we continue to face the repercussions of climate change, scientists and experts seek innovative ways to mitigate its impacts. Solar geoengineering (SG), a technique involving the distribution of aerosols

Razer Discount

Unbelievable Razer Blade 17 Discount

On September 24, 2023, it was reported that Razer, a popular brand in the premium gaming laptop industry, is offering an exceptional deal on their Razer Blade 17 model. Typically

Innovation Ignition

New Fintech Innovation Ignites Change

The fintech sector continues to attract substantial interest, as demonstrated by a dedicated fintech stage at a recent event featuring panel discussions and informal conversations with industry professionals. The gathering,

Import Easing

Easing Import Rules for Big Tech

India has chosen to ease its proposed restrictions on imports of laptops, tablets, and other IT hardware, allowing manufacturers like Apple Inc., HP Inc., and Dell Technologies Inc. more time

©2023 Copyright DevX - All Rights Reserved. Registration or use of this site constitutes acceptance of our Terms of Service and Privacy Policy.