In my previous post I told you about how to track user activity in your Silverlight application using Google Analytics. The real communication is done through a framework, called Microsoft Silverlight Analytics Framework. I have to admit that this framework lets you integrate your application with whichever analytics service in seconds. However, you need to add a few assemblies to your project – a fact which you may not be that happy with. Here is the list of these assemblies and their approximate size:
- System.Windows.Interactivity.dll ~36KB
- System.ComponentModel.Composition.dll ~242KB
- Microsoft.WebAnalytics.dll ~ 40KB
- Microsoft.WebAnalytics.Behaviors.dll ~34KB
- Google.WebAnalytics.dll ~ 23KB
In total you will add ~375KB to your XAP file (I don’t consider compression here). If you do not already use any of the first two assemblies, it is really senseless to add them only to support your tracking features.
I was in the same situation so I decided to write my own Google analytics tracker. The first thing to ask yourself is “How does Google analytics receives input?”. If you observe the requests your application makes (using Fiddler or Firebug) you will notice the following one:
http://www.google-analytics.com/__utm.gif?utmac=UA-00000000-0&utmcc=__utma%3D0.1536915019.1289736044.1289736044.1289736044.1%3B&utmwv=4.4wp7&utmn=1316222758&utmt=event&utme=5(Navigation*Navigated*Frame)(1)8()9()11()&utmcs=utf-8&utmul=bg-bg&utmsr=1440×460&utmsc=32-bit&utmdt=SilverlightAnalytics&utmp=/SilverlightAnalyticsTestPage.aspx/Views/Items.xaml?name=bag&utmhn=localhost&utmr=0
Interesting! The way Google analytics works is via a request to a GIF image. In the GET parameters of the request an application sends then necessary data to be tracked. This data includes browser title, domain, browsing path, browser resolution, etc. You can read more about GET parameters’ specification on Google analytics site.
Using the original code in Google.WebAnalytics.dll, I created my own analytics tracker which does not work with behaviors but with explicit calls.
1 2 3 4 |
public interface IAnalyticsTracker { void Track(AnalyticsData data); } |
There are two types – AnalyticsData (the base one) and AnalyticsDataEvent. Although I have tried to make it general (so that I can write my own tracker) these types are more or less Google-specific. So, to track user activity you can do the following:
1 2 |
GoogleAnalyticsTracker tracker = new GoogleAnalyticsTracker("API-key", analyticsImage); tracker.Track(new AnalyticsData() { RequestedPath = "/something"; }); |
You need to specify the Google analytics API and an Image object when creating the tracker object. You need an Image because it will be used to make the requests. NOTE: The Image should be already put on the visual tree. Otherwise it won’t make any request.
You can download the library package and try it out yourself.