using System; using System.Web.UI; namespace YourWebsite { /// /// Base page class for all web pages on your website. /// Indicate this in your Web.config file using the pageBaseType attribute of the pages element, /// and whenever you create a class that would normally derive from System.Web.UI.Page, derive from this instead. /// public class DefaultPage : Page { // Set this to your host name; as you can see below, it is used to detect whether or not the site is live (i.e. not localhost). const string hostName = "example.com"; // This is the code from Google that they have you inject inline, current as of 2008-11-11. const string gatInlineScript = @"var pageTracker = _gat._getTracker(""UA-5001336-1""); pageTracker._initData(); pageTracker._trackPageview();"; protected override void OnLoadComplete(EventArgs e) { // Only insert Google analytics code when we're on the live webserver; don't do it, for example, with localhost. if (this.Request.Url.Host.IndexOf(DefaultPage.hostName, 0, StringComparison.OrdinalIgnoreCase) != -1) { // Figure out which Google server to query; the Google sample code does this client-side. string gatUri = this.Request.IsSecureConnection ? "https://ssl." : "http://www." + "google-analytics.com/ga.js"; // If the page has a script manager, we'll add a script reference to that, and get all the related benefits; // otherwise, inject an include manually. ScriptManager scriptManager = ScriptManager.GetCurrent(this); if (scriptManager != null) { scriptManager.Scripts.Add(new ScriptReference(gatUri)); } else { this.ClientScript.RegisterClientScriptInclude("GATInclude", gatUri); } // Add this block of script inline at the bottom. this.ClientScript.RegisterStartupScript(this.GetType(), "GAT", DefaultPage.gatInlineScript, true); } // You might want to add custom logic here, specific to your site, and unrelated to Google analytics. // For example, on my site it uses the Web.sitemap file to compose this.Title (i.e. the page's title, in the titlebar of the browser). base.OnLoadComplete(e); } } }