2010-03-04

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).

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 SiteUtils-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.SiteUtils.RenderGoogleAnalyticsScript() %>
Updated 2010-06-03: slightly modified the generated JavaScript-code to better match the current official Google Analytics-script.
Updated 2012-03-22: made the generated JavaScript-code even smaller, and moved the code snippet to Gist.