Site and Page Counters
Counting page hits is a requirement for many large Web sites and hosting companies, and some excellent commercial packages provide a range of services to track and analyze data. However, there is often a need for a smaller, more localized set of services to track page hits or click-throughs.This has been implemented in ASP.NET 2.0 with an easy-to-use Site Counters Service, which tracks clicks and hits in a configurable data provider (Access and SQL Server being the supplied providers). The Site Counters Service tracks a number of pieces of information, such as the current page, the target page, named counter groups and counters, and the application name. Each unique combination of these results, within a configurable time period, results in the creation of a new counter and a new row in the database. Subsequent instances cause the counter to be updated.The database provides the columns shown in Table 12.8.
Column | Description |
---|---|
Id | A unique key, automatically generated. |
Application | The name of the application, as configured in the IIS metabase. |
PageUrl | The URL of the source page. |
CounterGroup | The group to which the counter belongs. |
CounterName | The name of the counter. |
CounterEvent | The event that generated the counter. This will either be Click or View, to indicate tracking of a click-through or a page view. |
NavigateUrl | The URL of the target page, if navigating. |
StartTime | The time tracking started for this counter. This time is dependent on the number of rows per day and is the time the counter interval started, not the time the first page was tracked. For example, with a RowsPerDay value of 24, the start time would always be on the hour. |
EndTime | The time tracking ended for this counter. |
Total | The total number of clicks/hits for this counter for this interval. |
Column | Access Data Type | SQL Server Data Type |
---|---|---|
Id | AutoNumber | int (Identity) |
Application | Memo | nvarchar(256) |
PageUrl | Memo | nvarchar(512) |
CounterGroup | Memo | nvarchar(256) |
CounterName | Memo | nvarchar(256) |
CounterEvent | Memo | nvarchar(256) |
NavigateUrl | Memo | nvarchar(512) |
StartTime | Date/Time | datetime |
EndTime | Date/Time | datetime |
Total | Number (Long Integer) | int |
Using Site Counters
The underlying implementation of site counters is an easy-to-use API that can be used directly or built into controls. The following list shows which controls have built-in support for the Site Counters Service:AdRotatorHyperLinkButtonImageButtonLinkButtonPhoneLinkImageMap
As these implement the service, they automatically have the option of exposing the properties shown in Table 12.10.
Property/Attribute | Description |
---|---|
CountClicks | Sets or returns a value that indicates whether or not the number of clicks is counted by site counters. |
CountViews | Sets or returns a value that indicates whether or not the number of views is tracked (e.g., each time an ad is shown). |
CounterGroup | Sets or returns the group name to which this counter belongs. If this is not specified, the default is the type of control being tracked. |
CounterName | Sets or returns the name of the counter. If this is not specified, the default is the name of the control being tracked. |
RowsPerDay | Sets or returns the maximum number of rows that will be stored in the logging database. The default value is 1, and the maximum value is 1440, indicating one row per minute. |
SiteCountersProvider | Sets or returns the provider used to log site counter data. If not set, the default provider from the application configuration file will be used. |
TrackApplicationName | Sets or returns a value that indicates whether or not the application name is tracked with the site counter details. The default value is True. |
TrackNavigateUrl | Sets or returns a value that indicates whether or not the URL of the target page is tracked with the site counter details. |
TrackPageUrl | Sets or returns a value that indicates whether or not the URL of the current page is tracked with the site counter details. The default value is True. |
<asp:Hyperlink runat="server" NavigateUrl="products.aspx"
Text="Product List" CountClicks="True" />
Every time this link is clicked, the details will be tracked. To add more details to the tracking, you can set more of the properties to differentiate different links:
<asp:Hyperlink runat="server" NavigateUrl="products.aspx"
Text="Product List" CountClicks="True"
CounterGroup="Products" CounterName="Overview"/>
<asp:Hyperlink runat="server"
NavigateUrl="products.aspx?ProductID=123"
Text="Special Offer" CountClicks="True"
CounterGroup="Products" CounterName="Special"/>
Here both links have the same CounterGroup but a different CounterName, ensuring they are tracked as separate items. To track items with different URLs as though they are the same (e.g., all hits on products.aspx no matter what the query string or which page the URL is on), the same CounterName can be used. Any session information stored as part of the URL is stripped before being logged.
When enabling counting on a control that navigates, the URL must be a virtual path. This means that you cannot turn on tracking for a control that has multiple navigation links (such as an ImageMap), some local and some remote. Remember that the Site Counters Service isn't designed to be an all-encompassing tracking system but a simple way to track local applications, so this implementation is deliberate. |
Using the Site Counters API
Access to the site counter data is available through an API exposed via the SiteCounters property on the Page. There are only two propertiesEnabled, to indicate whether the service is enabled, and a SiteCountersProviderCollection, which is a collection of all available site counters. The methods of the API are detailed in Chapter 6) will have details of the site counters (this is unavailable in the Technology Preview), but the Get methods allow you to provide your own interface if required. The Write method allows you to control the tracking of hits from within code. For example, although site counters do not allow absolute URLs, you could implement tracking of these manually, as shown in Listing 12.26.
Method | Returns | Description |
---|---|---|
Flush | Flushes the tracking information for a given provider to the database, or all providers if no provider is specified. | |
FlushAll | Flushes the tracking information for all providers to the database. | |
GetGroupRows | DataSet | Returns the rows for a given CounterGroup. |
GetNameRows | DataSet | Returns the rows for a given CounterName. |
GetNavigateUrlRows | DataSet | Returns the rows for a given source page URL. |
GetRedirectUrl | String | Returns the target URL given a selection of counter details. |
GetRows | DataSet | Returns the rows for a selection of counter details. |
GetTotalCount | Integer | Returns the total number of hits for a selection of counter details. |
GetTotalGroupCount | Integer | Returns the total number of hits for a given CounterGroup. |
GetTotalNameCount | Integer | Returns the total number of hits for a given CounterName. |
GetTotalNavigateUrlCount | Integer | Returns the total number of hits for a given source page URL. |
Write | Writes site counter details to the provider. |
Listing 12.26 Manually Adding URLs to the Site Counters Service
<script runat="server">
Sub NavigateAway(Sender As Object, E As EventArgs)
SiteCounters.Write("Navigate", "Away", "Click", _
"http://www.asp.net/", True, True)
Response.Redirect("http://www.asp.net/")
End Sub
</script>
<form runat="server">
<asp:LinkButton runat="Server" onClick="NavigateAway"
Text="ASP.NET" />
</form>
The Write method is overloaded and has several forms. See the documentation for complete details.
Configuring Site and Page Counters
The default installation of ASP.NET 2.0 ships with two providers for page trackingone for Microsoft Access and one for Microsoft SQL Serverand these are configured in the application configuration file. The syntax is shown in Listing 12.27.
Listing 12.27 Site Counters Configuration
<siteCounters
enabled="[true|false]"
defaultProvider="String"
handlerPath="String"
handlerType="String"
rowsPerDay="Integer"
type="String">
<providers>
<add
name="String"
type="string"
provider-specific-configuration />
<remove
name="string" />
<clear/>
</providers>
<pageCounters
enabled="[true|false]"
defaultProvider="String]"
rowsPerDay="[Integer]"
trackApplicationName="[true|false]"
trackPageUrl="[true|false]"
counterGroup="[String]"
counterName="[String]">
<pagesToCount>
<add path="String" />
<remove path="String" />
<clear/>
</pagesToCount>
</pageCounters>
</siteCounters>
The configuration is broken down into two sections. The first defines the properties and providers for the Site Counters Service itself (see Table 12.12).The <providers> element is where the actual site counter providers are added (see Table 12.13). The properties for the Access and SQL Server providers are the same.The attributes of the <pageCounters> element map directly to the properties we have already discussed, although by default page counters are disabled.
Property/Attribute | Description |
---|---|
enabled | Indicates whether or not the service is enabled. The default value is true. |
defaultProvider | Indicates the provider to use if no explicit provider is named. The default is the Access provider. |
handlerPath | Indicates the URL used to handle click-throughs. The default is ~/counters.axd, which is an HttpHandler that intercepts page clicks and tracks the data. |
handlerType | Defines the full name of the class that handles the site counter data. The shortened default is System.Web.Handlers.SiteCountersHandlerfull class details can be found in the configuration file. |
rowsPerDay | Defines the granularity with which data is logged to the provider. The default value is 1. |
type | Indicates the full class name of the default provider. |
Property/Attribute | Description |
---|---|
name | The name of the provider. |
type | The full class name of the provider. |
connectionStringName | The name of the connection string, from the connectionStrings configuration elements, that defines the connection details for the tracking database. This property is Access and SQL Server specific. |
description | A description of the provider. |
commitInterval | The interval, in seconds, between flushing the in-memory counters to the database. The default is 90. |
commitTimeout | The time, in seconds, to wait before aborting the database command that writes the counters. The default is 60. |
<pagesToCount>
<add path="*" />
</pagesToCount>
Wildcards can also be included as part of the path, for example:
<pagesToCount>
<add path="/*/default.aspx" />
</pagesToCount>
This ensures that only the default.aspx page is tracked, but only if one level down from the application root directory.
Only ASP.NET pages (.aspx) are supported and tracked by the Site Counters Service. All other pages are ignored. |
Configuring the Counter Database
You don't need to do anything specific to start using site counters, even though they are logged to a database. Because the default provider is Microsoft Access, when you first hit a page with site counters enabled, a new directory called DATA is created under your application directory if it doesn't already exist. Then a template database is copied into this directory and called ASPNetDB.mdb.For SQL Server there is no automatic installation, but a SQL Script, called InstallSiteCounters.sql, is included in the .NET Framework's installation directory.