Today I've been consolidating UserControls that I've found myself using in one EPiServer project after another into a nice Server Control library. One such control that gets used on every site (even non-EPiServer ones) is one which adds the Google Analytics JavaScript code to the page. I decided this would be the first UserControl to migrate.

Firstly I created a constant GoogleAnalyticsJavaScript which holds the JavaScript string to be added to the page. The only change I needed to make was to dynamically add the unique Google Analytics tracking code that was generated specifically for my domain. I could have stored this as a dynamic property in EPiServer, but decided that since it would hardly change, if ever, that the AppSettings would be a more suitable place. (This also makes the code more portable - sorry EPiServer!)

So I simply overrided the CreateChildControls and perform a quick check to make sure that there is a AppSetting with a Key of GoogleAnalyticsKey and that the script hasn't already been added to the page. Next i had to register it as a startup script (I chose startup script so it would be rendered near the end of body tag - perfect for situations where I want to add specific custom Google tracking to links within my page - I.e. downloads, RSS feeds etc. Registering a standard script block would appear at the top of the body meaning that custom link tracking wouldn't work).

The code listing is shown below:

public class GoogleAnalytics : InteraktingServerControl
{
    public const string GoogleAnalyticsJavaScript = @"
        <script type=""text/javascript"">
        /* Google TRACKING CODE */
        var gaJsHost = ((""https:"" == document.location.protocol) ? ""https://ssl."" : ""http://www."");
        document.write(unescape(""%3Cscript src='"" + gaJsHost + ""google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E""));
        </script>
        <script type=""text/javascript"">
        var pageTracker = _gat._getTracker(""{0}"");
        pageTracker._initData();
        pageTracker._trackPageview();
        /* Google TRACKING CODE */
        </script>";

    protected override void CreateChildControls()
    {
        //Make sure the Google Analytics key is set in the AppSettings
        //Also make sure the script hasn't been registered already
        if (!string.IsNullOrEmpty(WebConfigurationManager.AppSettings["GoogleAnalyticsKey"])
             && Page.ClientScript.IsStartupScriptRegistered(typeof(GoogleAnalytics), "GoogleAnalyticsKey" + ID))
        {
            Page.ClientScript.RegisterStartupScript(
                typeof(GoogleAnalytics),
                "GoogleAnalyticsKey" + ID,
                string.Format(
                    GoogleAnalyticsJavaScript, 
                    WebConfigurationManager.AppSettings["GoogleAnalyticsKey"]
                    )
                );
         }
        base.CreateChildControls();
    }
}

Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist
posted @ Wednesday, June 04, 2008 12:20 PM | in C# EPiServer .NET ASP.NET

Comments

Gravatar
# re: C#: Google Analytics Server Control
Posted by Steve Celius
on 6/5/2008 9:30 AM
Nice - and easy to use!

A couple of questions though:

Why do you add the id to the script key? Are there any cases where you'd want to add the Google script rendered twice?

Additionally, I've seen examples where the scripts at the end of the page needed to be in the correct order to work (some other buggy scripts, not the Google one). In that case, the control should be able to render the script at the position it is placed in the control hierarchy, not register it as a startup script.

/Steve
Gravatar
# re: C#: Google Analytics Server Control
Posted by Brad
on 6/5/2008 9:42 AM
Hi Steve

You're right - generally you'd only want it once. But for example our blogs have two tracking codes, one for the author, plus an overall one which does the entire blog. So for the sake of making the key unique i thought I'd add it.

I haven't come across the other script issues myself, so I'll bare that in mind.

Thanks for the feedback.

Post Comment

Title *
Name *
Email
Url
Comment *  


Please add 3 and 8 and type the answer here: