Unified Ad for Windows Phone - Part 2 - Basic Usage

Time for Part 2 of the Unified Ad for Windows Phone series. Also read part 1 for the introduction of the Unified Ad for Windows Phone. We covered the reason why we want the Unified ad for Windows Phone control and also registered for a couple of Ad Providers. Let’s start with implementing the Unified ad control in our application.

Install the NuGet Package for Unified Ad for Windows Phone

Start managing your NuGet Packages for your Windows Phone project. Search for “wpunifiedad” and click install.

Manage NuGet Packages, search for wpunifiedad

Go to one of your pages, for example “MainPage.xaml” and add the following Xaml in for example the ContentPanel Grid.

<Ads:AdControl x:Name="AdBasic"
                FallbackAdProviderName="AdDuplex"
                IsTest="True"
                xmlns:Ads="clr-namespace:MC.Phone.Ads;assembly=MC.Phone.Ads"
                xmlns:PubCenter="clr-namespace:MC.Phone.Ads.PubCenter;assembly=MC.Phone.Ads.PubCenter"
                xmlns:Smaato="clr-namespace:MC.Phone.Ads.Smaato;assembly=MC.Phone.Ads.Smaato"
                xmlns:MobFox="clr-namespace:MC.Phone.Ads.MobFox;assembly=MC.Phone.Ads.MobFox"
                xmlns:AdMob="clr-namespace:MC.Phone.Ads.AdMob;assembly=MC.Phone.Ads.AdMob"
                xmlns:Provider="clr-namespace:MC.Phone.Ads.Provider;assembly=MC.Phone.Ads"
                xmlns:AdDuplex="clr-namespace:MC.Phone.Ads.AdDuplex;assembly=MC.Phone.Ads.AdDuplex">
    <Ads:AdControl.AdProviders>
        <Provider:GenericAdProviderForXaml XamlUri="http://remoteurlontheinternet.com/Ad.xaml?appid={0}" />
        <Provider:NoneAdProvider />
        <AdDuplex:AdDuplexAdProvider App="" />
        <AdMob:AdMobAdProvider AdUnit="" />
        <MobFox:MobFoxAdProvider Publisher="test" />
        <Smaato:SmaatoAdProvider AdSpace="0"
                                    Publisher="0" />
        <PubCenter:PubCenterAdProvider Application=""
                                        AdUnit="" />
        <!--InnerActive is not really suitable for the Ad Rotation because it doesn't have any events to react on.-->
        <!--<InnerActive:InnerActiveAdProvider App="" />-->
    </Ads:AdControl.AdProviders>
</Ads:AdControl>

Lines 12 to 22 are the AdProviders that are available for the Unified ad control. Just remove the elements for the AdProviders that you’re not using or planning to use. For now also remove the GenericAdProviderForXaml element. This ad provider will be discussed separately in a next part. Also take a look at line 3, it is now configured to be run in Test mode. Now let’s start configuring the different ad providers.

AdDuplex configuration

After you added a new application to AdDuplex you will see the App ID. Copy this value to the App property of the AdDuplexAdProvider.

image

AdMob configuration

When you completed the configuration of a new site/app in AdMob you will see a so called Publisher ID. Copy this value to the AdUnit property of the AdMobAdProvider.

image

MobFox configuration

For MobFox you should copy the Publisher ID from the app to the Publisher property of the MobFoxAdProvider.

image

Smaato configuration

For Smaato you should fill in both the AdSpace and the Publisher number in the SmaatoAdProvider. Copy the AdSpaceId from the application list for your application to the AdSpace property for the SmaatoAdProvider. Copy the PubisherId below at that screen to the Publisher property for the SmaatoAdProvider.

image

PubCenter configuration

The PubCenter configuration consist of two parts. An Application, where you need to copy the Application ID to the Application property of the PubCenterAdProvider. And an Ad Unit where you need to copy the ID of the Ad Unit to the AdUnit property of the PubCenterAdProvider.

image

InnerActive configuration

InnerActive can be configured, but I cannot recommend using it in combination of the Unified Ad control. Inner Active doesn’t have any events that can be listened to like: NoAd, NewAd or AdEngaged. And because of this it’s impposible to let it rotate with the other Ad Providers. When you want to configure it though, you can. Copy the App Name and put it in the App property of the InnerActiveAdProvider.

image

Test or not?

You can put your AdControl in production mode by setting the IsTest property to False or completely removing the property from the Xaml.

The next part will be about the Remote Ad Provider configuration.

Unified Ad for Windows Phone - Part 1 - Introduction

About a month ago I started a new investigation about which Ad Provider I should use. Things I wanted.

- Best eCPM

- Best Fill Rate

- Easy to use

Some of the things that are causing problems is the Ad Availability per Country. Depending on where your app is used more or less localized ads are used. So we know that the Microsoft PubCenter has a high eCPM for the US, it is low for The Netherlands. There are more of those problems with other Ad Providers. I heard there was a solution for this problem. Use the Ad Rotator for Windows Phone 7 which can be found on Codeplex. I did give it a try but at that moment AdMob was not supported (mostly because there were some AdMob specific problems) and also MobFox and Smaato weren’t supported. Those were the specific Ad Providers I was interested in.

My initial though would be, let’s try to modify the source a little bit, to get support for MobFox and Smaato in. But after looking into the source I was warned, almost all the code was in the Code Behind for the AdControl. While I am not against the usage of the Code Behind, I’m pro extensibility. The code I saw was far from maintainable and extensibility is done by adding more code. So when more AdProviders will be added code will be less and less maintainable.

Unification

When I look at the differences between the AdControls, they more or less do the same, but in a different way. All of them have a TestMode, but enabling the testmode is different for each AdControl. Same for the events they have. I want to have a unified ad control that does handle these ‘Complexities’ for me and the rest of the world. There isn’t such a control yet, so why not use the good parts of wp7adrotator (the remote configuration, multiple adproviders) and create something that suits my needs better. So I did.

The Windows Phone Unified Ad control is universal in the following ways.

Properties:

- Country – Will be passed to all the AdProviders that support Country or Location as input

- IsTest – Will be pass to all the AdProviders that support a way of TestMode. Some have a simple boolean field, others require to set the PublisherId to be set to a specific value.

Events:

- NewAd – When a new ad is available this event will be fired, even though the different AdProviders have different events to notify the user, like: NewAdAvailable, AdLoaded, ControlAdRefreshed.

- NoAd – When no ad is availabe this event will be fired, even though the different AdProviders have different events to notify the user, like: AdFailed, ControlErrorOccurred, AdError.

- AdEngaged – When an ad is engaged or clicked this event will be fired, even though the different AdProviders have different events to notify the user, like: AdClick, ControlAdEngaged, ControlIsAdEngagedChanged, AdLeavingApplication. 

Best Fill Rate

To get the best fill rate the Windows Phone Unified Ad control supports ad provider rotation. As soon as an Ad Provider is not providing an ad the next Provider will be asked to provide an ad. This will enable you to get a higher fill rate compared to using just one ad provider. You can even roll in your own custom ad based on Xaml.

Best eCPM

Every single Ad Provider changes it’s eCPM from time to time. But they even have different eCPMs per country. Same as they might have, or might not have ads for a particular country at all. To get the best of both worlds Windows Phone Unified Ad control supports AdProviders per Country. Similar to the wp7adrotator, but instead the Country is used and not so much the full culture. If you already have configuration files for wp7adrotator you can use those as well, they are supported in the Windows Phone Unified Ad control as well.

Supported AdProviders

All Ad Providers that currently have an Ad Control for Windows Phone 7 are supported. Register with the ones you like best. Inner-Active support is experimental because they have no way to find out there’s an ad displayed or not, yet.

Microsoft PubCenter

AdMob

Smaato

MobFox

AdDuplex

Inner-Active

There are two special Ad Provider implementations.

- None – This ad provider is used to not show an ad at all. Can be very handy during testing phase, when testing the application and not the advertisements. But could also be used to show no ads for a certain percentage of the app usage.

- GenericAdProviderForXaml – This ad provider is used to show some custom Xaml that’s loaded from a remote url. Can be very handy to market your own applications within your own applications.

What’s next?

Next part will be about the basic usage of the Windows Phone Unified Ad Control. If you can’t wait? You can find the source and an example project with the Windows Phone Unified Ad control on codeplex. If you want to start right away you can add the NuGet Package called WPUnifiedAd. Also the homepage contains a basic guide that will help as well.

Part 3 will be about using the Remote Ad Provider Configuration. Future parts will come on how to make use of the GenericAdProviderForXaml

How to give an element focus when something happens?

I had a very simple problem: On loading of particular screen I wanted to give a TextBox focus. It’s freaking easy to do this in the code behind. Most of my applications are actually MVVM applications and in that case it’s not something for the ViewModel, it’s logic that belongs to the view. But how about a Behavior?

I want to give a specific control focus when something happens on something else. So that should be a TargetedTriggerAction<T>, T should be Control, because that’s something you can give focus. How easy can it be?

public class FocusOnEvent : TargetedTriggerAction<Control>
{
    protected override void Invoke(object parameter)
    {
        Target.Focus();
    }
}

Is that all? Yes it is, or actually, I want to make it even easier, add the default trigger using the DefaultTriggerAttribute. Default should be the Loaded event, so let’s add that single line.

[DefaultTrigger(typeof(FrameworkElement), typeof(EventTrigger), "Loaded")]
public class FocusOnEvent : TargetedTriggerAction<Control>
{
    protected override void Invoke(object parameter)
    {
        Target.Focus();
    }
}

Now we have this easy code, how do we use it? Just add a little bit of xaml to your page / control, just like any other behavior.

<i:Interaction.Triggers>
    <i:EventTrigger>
        <Behaviors:FocusOnEvent TargetName="TitleTextBox" />
    </i:EventTrigger>
</i:Interaction.Triggers>

Some second thoughts, is it required to take the Safe event Detachment base class for Windows Phone Behaviors by Joost van Schaik into consideration? No it’s not required, because we’re not manually attaching handlers to the events, that’s all done by the TargetedTriggerAction itself. Hope you guys think this little bit of code is useful.

Does Windows 8 support Gif images and Animated Gif images?

To some of us it may sound like a strange question, but developers which are used to Silverlight or Windows Phone development know why I ask this question. In both Silverlight and Windows Phone Gif images aren’t directly supported. Don’t ask me why, I don’t know why. Luckily Silverlight and Windows Phone developers are helped by an open source project called Image Tools which enables support for Gif and Animated Gif.

Windows 8 – HTML5 + JS

For a starter I just downloaded an ordinary gif-image from the internet and with no knowledge about how to add an image to a Windows 8 application I used my web-knowledge.

<img src="/images/window.gif" />

And yes it does work. What about an animated gif? So I recall an interesting animated gif on Shawn Wildermuth’s blog, his head-shot. So without do anything else than changing the source of the image tag I created it started working. A surprise? Not really I already heard that the rendering engine for Windows 8 applications that are build in HTML5 + JS is based on IE, so this is what I did expect.

Windows 8 – XAML + C#

So I used my Silverlight knowledge to do in XAML what I did in HTML5, add an image.

<Image Source="/Images/window.gif" />

A really fast surprise it started working in the design view of the xaml document even before I ran the project. And also after running the application it seems to work perfectly. And the animated gif? It appears in the designer as well, but doesn’t animate in there. Also when running the application the animation doesn’t work.

Just a quick thought: Silverlight doesn’t support gif at all, what about WPF? After some googling it seems that WPF does support gif images, but not really the animated gifs. But there are people who created solutions that should work to enable animated gifs in WPF. So let’s see how much of that is possible in Windows 8.

The solution for WPF makes use of the GifBitmapDecoder which isn’t there in Windows 8. But I found something that sounds similar the BitmapDecoder. I tried to get the a small proof-of-concept working, but failed so far. I invite you to solve this Animated Gif problem using the information I’ve given. Please share your solution with the readers of this post.

Conclusion

We all know WinRT isn’t finished, we are just looking at a developer preview. If I recall it correctly WinRT should have the same features in XAML+C# as in HTML5+JS. Will this small difference in features be tackled in the final release?

Statistics for your Windows Phone application (Google Analytics)

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.