Wednesday, April 29, 2009

Google Analytics in Silverlight

I’ve been trying to setup Google Analytics Event Tracking in a Silverlight application for a while and despite all the how-tos and artilces on the web, I just couldn’t get it running. I kept doing everything proposed, but when the application was run on IE, a javascript error was occurred. Firefox didn’t even bother reporting the JS error. So, if you happen to have the same problem, here’s how you should do it to get it working.

Event Tracking is when you want to track users accessing various parts of you RIA application, which works differently comparing to html based websites. The basic setup is almost the same: include ga.js javascript on your page hosting the Silverlight application. Include this snippet before </body> tag:

<script type="text/javascript">
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>
Next step would be to create a helper javascript function which we’ll call in our silverlight application. The script would help us track events on our silverlight application. Add this just below the above script:
<script type="text/javascript">
function trackPage(category, action, label) {
try {
var pageTracker = _gat._getTracker("xx-xxxxxxxx-x");
pageTracker._trackPageview();
pageTracker._trackEvent(category, action, label);
}
catch (err) {
}
}
</script>
EventTrackingIt is essential that calls to_trackPageview is made prior to calling _trackEvent.

Notice how the function is wrapped in a try-catch block so if there is any issues with ga.js loading, we silently ignore the tracking. Strangely, when there was any javascript error in IE 8, some parts of my silverlight application didn’t work properly. This helped getting around it.

Usually, you’d call an existing javascript in your silverlight app by calling it this way:
HtmlPage.Window.Invoke("functionName", new[] { args });
But to make things easier, let’s create an extension method to help us calling the tracking function:
public static class ViewExtension
{
public static void Track(this UserControl view, string action, string page, string label)
{
HtmlPage.Window.Invoke("trackPage", new string[] { action, page, label });
}
}
Just need to start tracking now!
Submit this story to DotNetKicks Shout it

No comments: