Statistics for your Windows Phone application (Google Analytics)

Update 06-07-2012: The world has changed. You can now do it in 1 minute!

Alright, I’ve tried a couple of different systems to get the statistics for the apps I created.

Google Analytics custom way

I started more than a year ago with a unreliable option using Google Analytics. This option was unreliable because it didn’t handle things like no connectivity and was depending on the WebBrowser control. Technically this was an option, but there are better options.

Flurry Analytics

My first applications actually did go live with Flurry Analytics for the stats. This worked perfectly fine for some time, until I introduced a application version that only supported Mango. Strangely I never got stats for that version. In the end I heard more people complaining that the Flurry Analytics library didn’t work with Phones running on Mango. I was not happy because it took weeks before I got a response from Flurry about the problem. They asked if I was interested in doing some beta-testing. I honestly didn’t have interest in beta-testing after that long time. I hear some rumors that it’s still not working, but I’m not sure, I’ve given up Flurry Analytics.

PreEmptive Runtime Intelligence

Alright, then I heard people say, why don’t you use PreEmptive’s Runtime Intelligence. It’s free and actually an Enterprise Product. I tried it, and actually liked it. The documentation on how to use it was not top-level, but with a little bit of trying out I got things working. But even better the tool integrates an Obfuscation tool to obfuscate the code. But then it started to take longer to get the stats processed. The last time my stats were processed is at October 6th, that’s 13 days ago, way to long. I understand that it can take some time, 24 hours is pretty acceptable. But more, every user of Runtime Intelligence got an e-mail to say that the conditions are about to change in two months time. This is basically because Microsoft has changed the contract with PreEmptive, but still, the new conditions are not clear, yet. Will it be paid, will it be limited? We don’t know yet. So for me, it’s time to look for a solid Analytics solution that I know will be free and will be supported by tools in the market.

Google Analytics with Microsoft Silverlight Analytics Framework

Alright, I’ve chosen to go back to Google Analytics and follow the comments I got from my readers on my custom Google Analytics tracking post. They suggest to make use of Microsoft Silverlight Analytics Framework. This framework supports a couple of very important scenario’s.

  • Offline scenarios
  • Support for multiple analytics services, including:
    • Comscore
    • Google Analytics
    • PreEmptive Solutions

Where I already have experience with implementing analytics using the custom PreEmptive tools I wouldn’t try that again, how long will it be free? I also have some experience with Comscore for one of my customers. I don’t understand how to read the reports so that’s not really an option for me, neither is it free. So Google Analytics it is, I know how to read the reports, and I’ve got a lot of experience implementing it for websites. Let’s start with the implementation in a Windows Phone application.

Step 1 Downloading and Referencing

You can download the source or the installation package. Be aware that the source doesn’t contain the source code for the Analytics Services like Google Analytics. So recommended will be the download of the installation package. After the installation you can find the libraries in: C:\Program Files (x86)\Microsoft SDKs\Microsoft Silverlight Analytics Framework\

You’ll need to reference the following libraries when working with Google Analytics:

  • Microsoft.WebAnalytics.dll
  • Microsoft.WebAnalytics.Behaviors.dll
  • System.ComponentModel.Composition.dll
  • System.ComponentModel.Composition.Initialization.dll
  • System.Windows.Interactivity.dll

Note: I’ve had some trouble with conflicting System.Windows.Interactivity libraries. It’s distributed with Expression Blend, MVVM Light and also with the Microsoft Silverlight Analytics Framework. I think there needs to be a solution so that the distribution should no longer be required for the different frameworks. I specially had a conflict when using Microsoft Silverlight Analytics Framework (made for Windows Phone SDK 7.0) in combination with MVVM Light 4 Preview (made for Windows Phone SDK 7.1). I did fallback to the previous version of MVVM Light 3 to remove the conflict.

Step 2 Create the IApplicationService and use reference it in App.xaml

Let’s start with gathering some generic information I want to gather from my users. To be honest I want to do this for all my applications. So this static class get's some information about the device. The PhoneHelper class can be found inside the Coding4fun library which also has other nice stuff. You could use this also for difference between Trial and Paying users.

public static class AnalyticsProperties
{
    public static string DeviceId
    {
        get
        {
            var value = (byte[]) DeviceExtendedProperties.GetValue("DeviceUniqueId");
            return Convert.ToBase64String(value);
        }
    }

    public static string DeviceManufacturer
    {
        get { return DeviceExtendedProperties.GetValue("DeviceManufacturer").ToString(); }
    }

    public static string DeviceType
    {
        get { return DeviceExtendedProperties.GetValue("DeviceName").ToString(); }
    }

    public static string Device
    {
        get { return string.Format("{0} - {1}", DeviceManufacturer, DeviceType); }
    }

    public static string OsVersion
    {
        get { return string.Format("WP {0}", Environment.OSVersion.Version); }
    }

    public static string ApplicationVersion
    {
        get { return PhoneHelper.GetAppAttribute("Version").Replace(".0.0", ""); }
    }
}

So let’s continue with our IApplicationService that wraps the WebAnalyticsService provided by the Analytics Framework. Just to prevent that my applications start to depend to much on Microsoft Silverlight Analytics Framework, I don’t want to change too much code when I need or want to switch next time. I explicitly set the Page Tracking to false because I want to be in control when and what to track. Further more I’m setting the CustomVariables that you might recognize from Google Analytics. There is a maximum of 5 Custom Variables and because the GoogleAnalytics library also puts the ApplicationId inside the Custom Variables you end up having only four for your application. That’s one of the reasons why I have the Device Type and Manufacturer concatenated in the Device property, choose carefully what you want to track. Next is the interesting part of Initializing MEF, I’m not an expert on MEF but basically it’s a kind of IoC container but differently. We will make use of the composition possibilities that we get from using MEF in a moment. The last part is the WebPropertyId which is passed to Google Analytics, this is the Google Analytics Property Id which is in the form of UA-XXXXX-X. So make sure you register a Google Analytics Web Property

public class AnalyticsService : IApplicationService
{
    private readonly IApplicationService _innerService;
    private readonly GoogleAnalytics _googleAnalytics;

    public AnalyticsService()
    {
        _googleAnalytics = new GoogleAnalytics();
        _googleAnalytics.CustomVariables.Add(new PropertyValue { PropertyName = "Device ID", Value = AnalyticsProperties.DeviceId });
        _googleAnalytics.CustomVariables.Add(new PropertyValue { PropertyName = "Application Version", Value = AnalyticsProperties.ApplicationVersion });
        _googleAnalytics.CustomVariables.Add(new PropertyValue { PropertyName = "Device OS", Value = AnalyticsProperties.OsVersion });
        _googleAnalytics.CustomVariables.Add(new PropertyValue { PropertyName = "Device", Value = AnalyticsProperties.Device });
        _innerService = new WebAnalyticsService
                            {
                                IsPageTrackingEnabled = false,
                                Services = { _googleAnalytics, }
                            };
    }

    public string WebPropertyId
    {
        get { return _googleAnalytics.WebPropertyId; }
        set { _googleAnalytics.WebPropertyId = value; }
    }

    #region IApplicationService Members

    public void StartService(ApplicationServiceContext context)
    {
        CompositionHost.Initialize(
            new AssemblyCatalog(
                Application.Current.GetType().Assembly),
            new AssemblyCatalog(typeof(AnalyticsEvent).Assembly),
            new AssemblyCatalog(typeof(TrackAction).Assembly));
        _innerService.StartService(context);
    }

    public void StopService()
    {
        _innerService.StopService();
    }

    #endregion
}

You can then add this ApplicationService to the ApplicationLifetimeObjects in the App.xaml file.

<Application.ApplicationLifetimeObjects>
    <!--Required object that handles lifetime events for the application-->
    <shell:PhoneApplicationService Launching="ApplicationLaunching"
                                    Closing="ApplicationClosing"
                                    Activated="ApplicationActivated"
                                    Deactivated="ApplicationDeactivated" />
    <Analytics:AnalyticsService WebPropertyId="UA-XXXXX-X" />
</Application.ApplicationLifetimeObjects>

This also enables automatic tracking Launch, Closing, Activated and Deactivated events in Google Analytics. So we don’t have to do anything manually to enable that part.

image

Step 3 Start tracking usage of features

Besides the starting and stopping of your application you probably want to track the usage of features in your app. You can make use of the TrackAction Behavior for example which can be found in Microsoft.WebAnalytics.Behaviors. But I actually like to have this kind of stuff in code which makes it easier for me to get an overview of what I’m tracking. So I wrote this simple AnalyticsTracker class that makes use of MEF to import the WebAnalytics stuff.

public class AnalyticsTracker
{
    public AnalyticsTracker()
    {
        CompositionInitializer.SatisfyImports(this);
    }

    [Import("Log")]
    public Action<AnalyticsEvent> Log { get; set; }

    public void Track(string category, string name)
    {
        Track(category, name, null);
    }

    public void Track(string category, string name, string actionValue)
    {
        Log(new AnalyticsEvent { Category = category, Name = name, ObjectName = actionValue });
    }
}

Usage is pretty straightforward.

AnalyticsTracker tracker = new AnalyticsTracker();
tracker.Track("Advertisement", "Refreshed", adUnit);

Step 4 Analyse the data

Alright start with Top Events

image

Cool but in which countries?

image

Of course there much more analytics that you can see inside of Google Analytics, this is just a start.

  • Gravatar joseharriaga October 23rd, 2011 at 01:57
    This is a great post.
    However, I'm getting an exception thrown by the App.xaml when I add the service to the ApplicationLifetimeObjects.
    The exception message is "The type Analytics Service was not found." and it's a XamlParseException.
    Do you have any what could be causing this?
  • Gravatar Mark Monster October 23rd, 2011 at 21:47
    Hi Jose, Most of the time you'll get these kind of messages until you did a build. The checking is done against compiled dll, not against the source. Hope this helps. Mark Monster
  • Gravatar joseharriaga October 23rd, 2011 at 22:09
    Yes, it's weird. Because it's built and even IntelliSense finds it, but it fails at runtime.
    I'll try experimenting with it a little bit more.
  • Gravatar Mark Monster October 24th, 2011 at 08:12
    Jose, Maybe you can find out if you're referencing the wrong version of System.Windows.Interactivity.dll. Are you referencing the one for WP7.1 or the one for WP7.0? It should be the one for WP7.0. I've had some trouble in combination with the latest version (4) of MVVM Light combined with MSAF. Hope this helps, Mark Monster
  • Gravatar Kwan October 25th, 2011 at 17:48
    Im new to all this Analytics , I am using preemptive but the reporting is not good and the data is lagging very bad. I am following you example here and it complie and run without problem. The next thing is how do i know my app able to track ? I only need to track the activate/deactive, how long the data will show up in Google Analytics ?

    Thank so much, it really help.

  • Gravatar Mark Monster October 25th, 2011 at 20:07
    Hi Kwan,

    You can see in a proximately 12 to 24 hours some data coming into Google Analytics. The Activate/Deactivate events are automatically tracked for you in Event Category "WP7", which you can find in Google Analytics under "Content" > "Events" > "Overview". The Event Action values contain the following values: Launching, Activated, Deactivated and Closing.

    Hope this helps a bit.
  • Gravatar Slobo November 12th, 2011 at 22:59
    I followed your example, but I am getting the following error:

    System.Windows.Markup.XamlParseException occurred
    Message=The type AnalyticsService was not found. [Line: 34 Position: 10]
    LineNumber=34
    LinePosition=10
    StackTrace:
    at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
    at MyApp.App.InitializeComponent()
    at MyApp.App..ctor()

    Do you have any idea what is causing it?
    Thanks, Slobo.
  • Gravatar Mark Monster November 15th, 2011 at 16:35
    Slobo,

    Maybe you can find out if you're referencing the wrong version of System.Windows.Interactivity.dll. Are you referencing the one for WP7.1 or the one for WP7.0? It should be the one for WP7.0. I've had some trouble in combination with the latest version (4) of MVVM Light combined with MSAF.

    Hope this helps,

    Mark Monster
  • Gravatar Nathan November 27th, 2011 at 13:36
    any idea where we can find the v7.0 of System.Windows.Interactivity.dll?

    thanks, Nathan
  • Gravatar Mark Monster November 28th, 2011 at 09:25
    Hi Nathan,

    On my machine it could be found under: C:\Program Files (x86)\Microsoft SDKs\Expression\Blend\Windows Phone\v7.0\Libraries

    Hope this helps,

    Mark Monster
  • Gravatar Manoj December 2nd, 2011 at 17:26
    Hi Guys,

    I am not found "GoogleAnalytics" anywhere ,
    So please help me how to resolve this issues.

    Manoj
  • Gravatar Manoj December 5th, 2011 at 10:11
    Hi ,
    where i find "GoogleAnalytics" in (which namespace or dll ) , i am unable to use above class as it creates a compile time error.

    Thanks
    Manoj
  • Gravatar Mark Monster December 5th, 2011 at 21:46
    Hi Manoj,

    The Google Analytics library is shipped as part of the install package. You should be able to find it in the install folder of MSAF.

    Hope this helps,

    Mark Monster
  • Gravatar Nick December 18th, 2011 at 17:22
    I am trying to read your page, not your tag cloud. Does it have to keep moving?
  • Gravatar Slobo January 4th, 2012 at 01:32
    Replacing System.Windows.Interactivity.dll with the old version has fixed the issue. Thx!
  • Gravatar Rico January 10th, 2012 at 13:34
    Hi Mark

    Thank you for your article, it is working for me on WP7.1. I have one question as I don't know Google Analytics very well: In the the first image of "Step 4 Analyse the data" you have a total of 62 WP7 Launching events and 24 unique events. Does this mean the app has been started 62 times in total and 24 on different devices? If a single user starts the app multiple times does this result in only one unique event?

    Thanks.
  • Gravatar gyurisc February 16th, 2012 at 08:14
    Very good article. I was just thinking somehow putting GA into my own app and your article gave me the answer. On the other hand I thought that GA is only for websites. I was wondering if this is a valid way to use Google Analytics? Is google not going to punish me for using their services this way?
  • Gravatar Rob de Beir February 29th, 2012 at 15:47
    Hi,

    Just played with a "light" alternative for MSAF, see http://codecube.net/ and https://github.com/maartenba/GoogleAnalyticsTracker

    Might be interesting to include in your post. Have crated a small application with this tool, hopefully will see the statistics tomorrow.

    Note: This afternoon did not succeed in installing the NuGet package for this tool, instead used the source code from Github and added the NuGet package "Task Parallel Library fro Silverlight"
  • Gravatar Mark Thomas March 20th, 2012 at 22:24
    Hi Mark,
    Thanks for a great article that got me kickstarted with Google Analytics.
    Unfortunately I get an exception adding the xaml:
    Add value to collection of type 'MS.Internal.ApplicationLifetimeObjectsCollection' threw an exception. [Line: 31 Position: 41]

    The Xaml is:
    <Application.ApplicationLifetimeObjects>
    <!--Required object that handles lifetime events for the application-->
    <shell:PhoneApplicationService
    Launching="Application_Launching" Closing="Application_Closing"
    Activated="Application_Activated" Deactivated="Application_Deactivated"/>
    <HelperClasses:AnalyticsService WebPropertyId="UA-XXXXXXXX-1" />
    </Application.ApplicationLifetimeObjects>

    I am using the 7.1 version of System.Windows.Interactivity.dll as the 7.0 version doesn't work with the newest version of Google.WebAnalytics.dll

    Thanks.
  • Gravatar Aditya March 23rd, 2012 at 07:00
    How to get page views value?
  • Gravatar Leonard April 2nd, 2012 at 12:59
    Hi Mark,

    Thanks for the great post. I do have a question: where can I find the "GoogleAnalytics" dll? It is not in the "C:\Program Files\Microsoft SDKs\Microsoft Silverlight Analytics Framework.4\Install" folder.

    Regards, Leonard
  • Gravatar Nagarajan April 23rd, 2012 at 09:42
    Hi Slobo,

    i will got this type error in Google analytic.. please help
    System.Windows.Markup.XamlParseException : "The type 'AnalyticsService' was not found. [Line: 21 Position: 37]"
  • Gravatar Alishakool April 25th, 2012 at 09:30

    getting error "GoogleAnalytics is namespace but used like a type"

    in AnalyticsService class in line " private readonly GoogleAnalytics _googleAnalytics;"

    Please help...



  • Gravatar _Chilling August 23rd, 2012 at 01:08
    Thank you for sharing this great article.

    I have tried this and the easy solution that your provided, but I dont see the analytics of page views (not even 1 page view). How do I debug this ?

    Also, it would be great if you could provide a simple basic VS solution that works. Specially for stuff like, how to track how many times a button was clicked.

    If you are busy, can anyone else with the right expertise please help out ! Thanks !
  • Gravatar George Kosmidis September 9th, 2012 at 11:56
    Microsoft.SilverlightMediaFramework.Compatibility.Phone.dll replaces System.ComponentModel.Composition.Initialization.
  • Gravatar Nico Dekker November 15th, 2012 at 10:58
    Hi Mark,

    Great article but one important question. How do you exactly set up the Google Analytic account to capture statistics from a WP7 app?

    Thanks,
    Nico Dekker
  • Gravatar Vicente Guzman December 4th, 2012 at 00:12
    Hi Mark,

    Do you have some example or proyect when use the DLL of Flurry?
    I try use this for an App of WP but I don´t know how.
    Can you helpme?

    Thanks.
  • Gravatar Pardeep February 13th, 2013 at 14:39
    Helloo Mark,

    I'd implement GA in my VS2010 sdk by using App version 7.1 . But i got an Exception as:

    XAMLPARSED EXCEPTION OCCURRED :-
    Add value to collection of type 'MS.Internal.ApplicationLifetimeObjectsCollection' threw an exception. [Line: 8 Position: 25]

    Plz Help me regarding this. Waiting for your help !!

    Thank You !!
  • Gravatar proudtobecheesy.co.uk April 6th, 2014 at 15:58
    Hey there! I just wanted to ask if you ever have any trouble with hackers? My last blog (wordpress) was hacked and I ended up losing months of hard work due to no back up. Do you have any methods to protect against hackers?
  • Gravatar JessieTide April 13th, 2014 at 03:25
    |

    http://wj9.volaratenerife.com/
    http://6a8.724ukpaydayloansuk.co.uk/
    http://1z6.volaratenerife.com/
    http://x7l.paydayloansuk2011.co.uk/
    http://3h9.amlinguistics.com/
    http://pb5.iditratson.com/
    http://6f7.ukpaydayloansuk2012.co.uk/
    http://ua3.724ukpaydayloansuk.co.uk/
    http://0o2.iditratson.com/
    http://s9s.ukpaydayloansuk724.co.uk/
    http://7x5.paydayloansuk2012.co.uk/
    http://9w3.zionsvilleindianarealestate.com/
    http://u2u.ukpaydayloansuk2013.co.uk/
    http://nu0.cheshirepellet.com/
    http://h0r.ukpaydayloansuk2012.co.uk/
Gravatar