Google Analytics in ASP.NET

Here’s a little C# function I occasionally use to insert a Google Analytics-snippet in an ASP.NET website. It takes a Google Analytics-ID as an argument, which you can leave blank in debug-mode (to not render the snippet). It uses the recently introduced asynchronous loading method (which doesn’t block the rendering of your website). It’s not literally the same snippet you can find on the Google Analytics site, but it does the same thing (only with a slightly smaller dynamically built JavaScript-snippet).

using System;
using System.Web;
namespace TC
  public static class GoogleAnalytics
    public static string RenderScript(string googleAnalyticsID)
      return string.IsNullOrEmpty(googleAnalyticsID)
        ? ""
        : "<script>"
        + "var _gaq=_gaq||[];"
        + "_gaq.push(['_setAccount','" + googleAnalyticsID + "']);"
        + "_gaq.push(['_trackPageview']);"
        + "(function(d,s){"
        + "var e=d.getElementsByTagName(s)[0],"
        + "x=d.createElement(s);"
        + "x.async=1;"
        + "x.src='"
        + (HttpContext.Current.Request.IsSecureConnection
            ? "https://ssl" : "http://www")
        + "';"
        + "e.parentNode.insertBefore(x,e)}(document,'script'))</script>";

I usually keep the Google Analytics-ID in my application settings (web.config), which allows me to use a different one for different deployments (or an empty one for debugging). So I have a second function (in a SiteUtilities-class) that doesn’t take an argument, but takes the Google Analytics-ID from the settings:

public static string RenderGoogleAnalyticsScript()
  return TC.GoogleAnalytics.RenderScript(Settings.Default.GoogleAnalyticsID);

In my master-page, I then use the following snippet to insert it into the body of the page (note that you have to use the fully qualified type name, including namespace):

<%= MyNamespace.SiteUtilities.RenderGoogleAnalyticsScript() %>