Monday, November 17, 2014

BLE on Windows Phone 8.1 (and Xamarin.Forms)


Introduction / Compatibility

BLE or Bluetooth Low Energy is a bit of a funny story when it comes to Windows Phone.  The technology was created by Nokia back in 2006, but both iOS and Android added support for it in their mobile devices well before Windows Phone.  Even worse, it sounded like BLE would work on Windows Phone 8 almost 2 years ago but the simple truth is: you currently need a Windows Phone 8.1 Nokia device running at the least the Cyan update.  The “color” updates are alphabetical so Denim will work, (eggplant?), some color that’s starts with f, etc. 

You can check on update availability for Nokia Lumia devices here: 

I’ve personally been using a Rogers Nokia Lumia 920 and T-Mobile Lumia 521.  Both work well after the Cyan update.

Connecting to BLE Devices from Windows Phone

So BLE was designed to avoid needing to “Pair” devices like we do with traditional Bluetooth.  But strangely, on Windows Phone 8.1 you still need to pair with BLE devices, unlike iOS and Android.  This means opening up your Bluetooth Settings and selecting your target device.




The upside to this is, your Windows Phone doesn’t need to search for new devices every time you want to use BLE in your application.  The downside is, Windows Phone doesn’t search for new devices and therefore doesn’t verify automatically that your paired device is present.

Windows Phone 8.1 Capabilities (Permissions)

You’ll also need to specify BLE capability in your Package.Appmanifest.  Currently Visual Studio doesn’t offer BLE in capabilities selector so you’ll need to edit the file manually.



First you’ll want to include “internetClientServer” capability:

<Capability Name="internetClientServer" />


And then specify a DeviceCapability:


<m2:DeviceCapability Name="bluetooth.genericAttributeProfile">

You can then specify a BLE device specifically but to make things simple I recommend using “any”


<m2:Device Id="any">


Finally, you need to specify which services you’re going to be using with the BLE device, which you can do by category or Guid:

<m2:Function Type="name:genericAccess" />

<m2:Function Type="serviceId:713d0000-503e-4c75-ba94-3148f18d941e"/>


If you’re not sure what services you’ll be using you can just list all of the categories:

<m2:Function Type="name:genericAccess" />

<m2:Function Type="name:alertNotification" />

<m2:Function Type="name:battery" />

<m2:Function Type="name:bloodPressure" />


<m2:Function Type="name:txPower" />

A simple complete example to communicate with the RedBear Labs BLE Mini:


  <Capability Name="internetClientServer" />

  <m2:DeviceCapability Name="bluetooth.genericAttributeProfile">

     <m2:Device Id="any">

        <m2:Function Type="name:genericAccess" />

        <m2:Function Type="serviceId:713d0000-503e-4c75-ba94-3148f18d941e"/>





Windows Phone 8.1 Projects

You will need to make a project targeting Windows Phone 8.1 to use BLE in your application, but there are actually two APIs you can use and they are not equal.

The more complete API set is in the new Windows Phone Store app model which uses the RT APIs.  Windows Phone Silverlight 8.1 is said to contain about 90% of the Store API but apparently some of the BLE APIs fall into the missing 10%.

Specifically, it’s missing the ability to generally search for Gatt Characteristics.  As long as you know the Guids for your characteristics this shouldn’t be an issue.  But you will come across more example code using the Windows Phone Store APIs.

Now if you’re a Xamarin.Forms developer like I am, you’re going to be using the Silverlight APIs.  The good news is, you can upgrade your Xamarin Forms Windows Phone projects to Silverlight 8.1!


Code Example

I’ll add some coding specifics on here soon, but for now, you can take a look at a Windows Phone 8.1 Silverlight example app here:

Wednesday, October 29, 2014

Get up and running with the Xamarin Android Player (and Google Play Services)

At Evolve 2014, Xamarin announced their very own Android simulator to help take some of the pain out of Android development. 

It’s hardware accelerated on both Intel and AMD platforms, runs on Windows and OSX, and it integrates very nicely with Xamarin Studio.  You no longer have to open your emulator of choice first and hope your dev environment finds it – Xamarin Studio will actually start it for you if its not already running.

But I’ll note here – you will need an active Xamarin Android account in order to run it (sorry Java developers).

It is currently in Alpha but it’s been working beautifully for me so far – grab the alpha here:

I won’t bother walking you through the installation steps, all you need to do is download and run the installer.  And then download the images for the Xamarin Android Player to use (at the time of writing there are two Nexus 4 images).


It’s fairly straight forward, and there’s a great guide here:

I’ve personally installed it on a Windows 8.1 64 machine and two Macs running OSX 10.9.5 & 10.10.  All three installed and ran without any issues.


Once you’re up and running, you may see some some cryptic error messages when trying to deploy your app to the Xamarin Android Player.

First, close everything down, restart Xamarin Studio and try again.  If that still doesn’t work, you may need to update the Android SDK Tools from the Android SDK Manager.  I have one Mac working with 23.0.2 and 2nd with 23.0.5.  Anything older may not work.


Google Play Services

Finally, you’re probably going to want to install Google Services on the Xamarin Android Player.  This will allow you to test your applications that make use of the Google Maps API. 

To get the Google Services running and enable mapping support, you’re going to install a Google Apps package (GApps).  And it’s very important you install the correct package for the version of Android your running in the Android Player. I found has the best descriptions for the app packages:

For the Nexus 4 (Jelly Bean) image you’ll want to install 20121011 

Unfortunately RootzWiki doesn’t currently have a KitKit package so you can grab it from

for the Nexus 4 (KitKit) image use CM 11 20140606


Make sure you download the Zip file(s) intact, Safari on Mac OS likes to automatically extract zip files so you may need to adjust your settings.

Safari > preferences > General > uncheck "Open safe files after downloading"


Once you’ve downloaded the zip files for the respective emulator images, it’s simply a matter of starting the emulator and dragging the zip file onto the Xamarin Android Player.


After you drag the corresponding zip file onto the running Xamarin Android Player, it will reboot and take 20+ seconds to restart.

The final step is to update your Google apps, this will help to make sure you have the latest version of the Google Play Services installed.  To do this, you’ll want to open the newly installed Google Play Store app, log in with a valid Google account, and update any installed Google applications.  You may see some errors popping up saying that Google play needs to be re-installed.  You can ignore them, they’ll stop once you have everything up to date.






And now you’re all set to use Google Play Services including Maps on the Xamarin Android Player.

You’ll of course need to follow the above steps for both Android images and you’ll likely need different zip file packages corresponding to the correct version of Android for future Xamarin Android Player Images.


Bonus Link:

If you want maximum performance but you don’t want to remove Hyper-V on your Windows machine – see Scott Hanselman’s blog on adding Hyper-V boot options on Windows 8.1:

*Follow up – Jan 20th, 2015

I just tested this out with the new emulator images available with build 0.2.5 and everything seems to be working as expected on both Windows and OSX

Wednesday, October 15, 2014

Getting Permission to Access User Location in iOS8 with Xamarin iOS

If you’ve been developing location aware applications for iOS for a while you know that you could simply attempt to access location data in your code.  And the first time your app was run on a device, it would ask the user for permission, hopefully they say yes, and things are easy.

There are a few additional steps now in iOS 8.

The first thing you need to do is add one or two keys to your applications info.plist.  You can do this by hand with a text editor or click on the info.plist files and use the “Source” view from within Xamarin Studio.

If you’re just using location data in a normal application, the key is:

NSLocationWhenInUseUsageDescription which is a string type.  The string value is the message that will be displayed to the user the first time your application attempts to receive location data. 

Alternatively, if you’re application is background enabled for location data, you would use:

NSLocationAlwaysUsageDescription which again has a string value.

The idea with these keys, is that you can now describe to your users why you require location information.  Alternatively, you can leave the values blank to show a generic popup message.

The new keys in your info.plist would look like this:

<string>In order to track your running routes</string>

or for a background enabled app without a custom message:





Additionally, in your code you now need to specifically request authorization by calling a method defined on an instance of the LocationManager class.  RequestWhenInUseAuthorization () for standard applications and RequestAlwaysAuthorization () for background enabled apps.


1 if (CLLocationManager.LocationServicesEnabled)
2 {
3 LocMgr = new CLLocationManager();
5 ...
7 // request permission
8 LocMgr.RequestWhenInUseAuthorization ();
9 // Start location updates
10 LocMgr.StartUpdatingLocation ();
12 ...
13 }


Thursday, September 4, 2014

How to add an iOS Image Set to an Asset Catalog using Xamarin Studio


With the official launch of iOS 8 just around corner, I thought it was time to get up to speed on on Asset Catalogs, and with that, Image Sets.

Image Sets allow you to organize versions of your images in image sets, and then add these sets to an Asset Catalog.  This will allow you to create multiple versions of the same image and have iOS automatically load the create version at runtime depending on the device.

Traditionally this would be used for providing regular and retina assets, as well as adding different versions depending on the idiom (ie iPhone / iPad).  And Apple has made it clear this year at WWDC 2014 that this is going to be much more powerful when using Universal Story boards and storing different versions of the image based on traits (but that’s a whole other conversation).

So let’s see how we go about creating an Image Set in Xamarin Studio.  The first thing we need to do is create an Asset Catalog:

Right click on your project and select “Add” –> “New File” and then select “Asset Catalog”.


Give it a name and click the “New” button.

By default the asset catalog includes Image Sets for application icons and launch images.  And this is a great way to keep them organized, but if you’re adding your application assets manually you can delete these two sets.

Next, right click on the Asset Catalog and select “Add” –> “New Image Set”


Now just click on the content.json file and drag files from finder to the appropriate location.   Currently you can set universal assets as well as adding device specific assets (iPhone / iPad) and I’d expect to see further support for traits when iOS 8 is officially released.


Thursday, June 19, 2014

Using WiDi on the Dell XPS 12 running Windows 8.1

There seems to be a bit of confusion on how to get WiDi up and running on some newer devices, especially if they don’t ship with the WiDi software pre-installed.  This was the case with my Dell XPS 12.

So really, all you need to do is go here but I’ll walk through some of the steps since things have changed since Windows 7 and the documentation hasn’t all been updated: 

Go to the link above and run the WiDi update tool – it’s going to make sure you have all of the nessesary drivers up to date.  After a fresh Windows 8.1 installation the WiDi updater upgraded my WiFi drivers to version 17.x.

On Windows 8.1 you no longer need a stand-alone WiDi app, it’s integrated into Windows.

Step 1: Turn on your TV & WiDi receiver, and make sure you can see the WiDi connection screen on your TV.  I’m using the NetGear PTV3000.

Step 2: Open the charms bar (swipe in from the right) and click on “Settings” and then “Change PC Settings” at the bottom of the charm flyout.

Step 3: Select “Display” on the left and then scroll to the bottom and click on “Connect to a wireless display”.

Step 4: Click “Add a wireless display” on the flyout.


Step 5: Allow Windows to search and then select your WiDi device from the list







My display lags slighlt when connected, but it works very well and the connection is stable.

If you’re having connection problems, make sure your WiDi receiver’s firmware is up to date.  I did need to update my Netgear PVT3000.

Friday, June 13, 2014

Detecting 2 in 1 state in WPF C# (Slate or Clamshell mode)

I’ve been wanting to experiment with changing UIs in my code between “tablet” mode and the “laptop” mode on my new Dell XPS 12 (or any other Ultrabook 2 in 1 that happened across my desk).  There’s already a really great article on how us developers can detect the state change on Intel’s developer portal; but the example code is in C++ and not my preferred C#.
Before we go any further, I recommend heading over to and reading Detecting Slate/Clamshell Mode & Screen Orientation in a 2 in 1.
The code we’re looking to implement is basically this (done in a WndProc):

   2:     if (wcscmp ( TEXT ("ConvertibleSlateMode"), (TCHAR*)lParam ) == 0)

   3:         NotifySlateModeChange ();

   4:    else if wcscmp ( TEXT ("SystemDockMode"), (TCHAR*)lParam ) == 0)

   5:         NotifyDockingModeChange ();
Simply stated, we need to monitor WM_SETTINGCHANGE or equivalent, detect which state we’re in, and respond accordingly.
Now that we know what our goal is, let’s make it work in a modern WPF C# application.  I looked a few approaches before settling on my solution, and hopefully it will make sense why I’ve done it this way as we work through the code.
Our first step is to import user32.dll so we can define and use the GetSystemMetrics method.

   1: public partial class MainWindow : Window

   2: {

   3:     [DllImport("user32.dll")]

   4:     static extern int GetSystemMetrics(SystemMetric smIndex);

   5:     ...

To do that we’ll need to reference the InteropServices:
using System.Runtime.InteropServices;
At this point you may have noticed that we don’t have the SystemMetric enum defined.  We could create our own with just the two metrics we need, but we might as well jump over to and get a fairly complete enum, and just copy that into our window class or somewhere else convenient (this might just be useful for other purposes as well): 
Unfortunately this list doesn’t contain the two metrics we want to check against as we saw in the Intel doc, namely
so we’ll add these to the end of the enum ourselves:

   1: public enum SystemMetric

   2: {   

   3:    ...    

   4:    SM_CONVERTABLESLATEMODE = 0x2003,    

   5:    SM_SYSTEMDOCKED = 0x2004

   6: }

(* after writing this post I decided I should update the page so the enum should now be up to date)
We’re almost ready to watch for the 2 in 1 state change.  In C++ we would just capture the WM_SETTINGSCHANGED message.
We could do this in C# by overriding OnSourceInitialized() and hooking into the WndProc.  Truth be told this was my first approach.  But on my machine I wasn’t receiving “SystemDockMode” from the lParam – it would always give me “ConvertableSlateMode” regardless of the state.  
So I decided to do it the “C# way” and just watch UserPreferenceChanging.  To try it out just add 

   1: SystemEvents.UserPreferenceChanging += SystemEvents_UserPreferenceChanging; 
to the constructor and create a method with the correct signature.  You’ll need to include “using Microsoft.Win32;” for SystemEvents.
We’ll get a UserPreferenceChanging event every time the device changes state, and it will come in under the General Category of UserPreferenceCategory. This is passed in with the UserPreferenceChagingEventArgs.  Unfortunately we don’t get any additional information, and we don’t have access to the lParam as we would if we were handling the message directly.
And that’s where the GetSystemMetrics() method comes in.  We’ll simply query for the state every time we change comes in under the General category.  Uou’ll likely want to add some logic to remember your current state and only update your UI if it changes.
See the code below: 

   1: void SystemEvents_UserPreferenceChanging(object sender, UserPreferenceChangingEventArgs e)

   2: {    

   3:     if(e.Category == UserPreferenceCategory.General)    

   4:     {        

   5:         if (GetSystemMetrics(SystemMetric.SM_CONVERTABLESLATEMODE) == 0)        

   6:         {            

   7:             Debug.WriteLine("detected slate mode");        

   8:         }        

   9:         else if (GetSystemMetrics(SystemMetric.SM_SYSTEMDOCKED) == 0)        

  10:         {            

  11:             Debug.WriteLine("detected docked mode");        

  12:         }    

  13:     }

  14: }
And that should give you everything you need to get started making 2 in 1 C# apps in WPF. 

Finally, there’s a sample project with all of the above code on github here:


Happy Coding!

Monday, June 2, 2014

Window Phone 8 Assets / Icon / Tile sizes


If you’ve tried to find the recommended tile sizes for Windows Phone 8.x you probably ended up here: 


And you definitely should read this article carefully.  However if you’re just looking to make some simple static assets for your Windows Phone 8 app its not obvious what’s required and or what’s best practice.

SO here’s this list:

  Scale 100 Scale 140 Scale 240
Square Logo 71x71 99x99 170x170
Logo 150x150 210x210 360x360
Logo Wide 310x150 434x210 744x360
Small Logo 44x44 62x62 106x106
Store Logo 50x50 70x70 120x120
Badge Logo 24x24 33x33 58x58

You’ll notice a couple of them overlap with Windows Store (but not many).


And for the Splash / Launch Images you’ll want to make:

480x800, 672x1120 & 1152x1920


If I come across a good site or tool for auto creating the icons I’ll make sure to add it here. 

For more information:

Thursday, May 22, 2014

Using the Dolby Audio API in Xamarin.Android

This is a continuation of my previous post on creating a Java Bindings Library for the Dolby Audio API.  If you haven’t already, you can read it here:

Xamarin Java Bindings Library Example using the Dolby Audio API for Android

Now I’d like to take a look at leveraging the Dolby Audio API from within a Xamarin.Android App.

About the Dolby Audio API 

The Dolby Audio API enables mobile developers to access, enable, and benefit from the Dolby technology incorporated in licensed mobile devices.  The enhanced capability is royalty free to an application developer.

A developer can set one of four predefined profiles: Movie, Music, Game and Voice. Each of these profiles is tuned to achieve the the best audio quality in its particular use case.

*From the Dolby Audio API documentation



Dolby Audio API for Android:

Visual Studio 2012/2013 (optional):

And finally, you’ll need to download the binding project from GitHub:

You’ll very likely also want an Android device with Dolby hardware for testing, you won’t be able to enable Dolby Audio Processing without one.  The new Kindle Fire HD & HDX devices are Dolby enabled.

Getting Started

To get started, download the binding project from GitHub, and open the solution in either Visual Studio or Xamarin Studio. 

You’ll need a business license of Xamarin.Android to use Visual Studio.  Officially, VS 2012 & VS 2013 are supported, but this project will also work in Visual Studio 2010.

Next, extract the contents of the Dolby Audio API zip, open the “Library” folder, and drag/copy “dolby_audio_processing.jar” into the Jars folder of the “DolbyAudioAPI” project, which is the binding project itself.


You should now be able to build the binding project (DolbyAudioAPI).  If it builds successfully, can either reference the project in a new Xamarin.Android project, or find the compiled “DolbyAudioAPI.dll” in the “bin” folder and reference it directly.

Using the Dolby Audio API for Android in C#

Fortunately, the binding project does a pretty good job of encapsulating the java properties and methods. So we can read Dolby’s own Java documentation and follow along.  However, there are some subtle differences.

In order to use the Dolby Audio API, you really just need two things:

an instance of DolbyAudioProcessing

and a class that implements IDolbyAudioProcessingEventListener

Let’s setup a simple Android Activity that also implements IDolbyAudioProcessingEventListener

using Com.Dolby.Dap;
public class Activity1 : Activity, IOnDolbyProcessingEventListener
   static DolbyAudioProcessing mDolbyAudioProcessing;

Next we’ll instantiate mDolbyAudioProcessing in OnCreate

protected override void OnCreate(Bundle bundle)
    mDolbyAudioProcessing = DolbyAudioProcessing.GetDolbyAudioProcessing(this, DolbyAudioProcessing.PROFILE.Music, this);


To get a DolbyAudioProcessing instance, we call the static method GetDolbyAudioProcessing(..) on the DolbyAudioProcessing class which takes three arguments:

Context p0 – the application context, or simply, the current Activity (this).
DolbyAudioProcessing.PROFILE p1 - Profile used to initialize the Dolby audio processing instance, the DolbyAudioProcessing.PROFILE.MOVIE profile will be used by default if it is null.
IOnDolbyAudioProcessingEventListener p3 - a class the implements IDolbyAudioProcessingEventListener for receiving events from the Dolby audio processing background service.  In our case, again its our current activity (this).
DolbyAudioProcessing should not be instantiated directly, and you should only call GetDolbyAudioProcessing(..) once during the lifetime of your application.  If you call it a 2nd time without first releasing, an exception will be thrown.

Implementing IDolbyAudioProcessingEventListener

You’ll need to create four methods that will called allow you to monitor the state of the Dolby Processing hardware:

void OnDolbyAudioProcessingClientConnected();
Will be called when a connection has been made to the Dolby audio processing background service.

void OnDolbyAudioProcessingClientDisconnected();
Will be called when an abnormal disconnection from the Dolby audio processing service occurs.

void OnDolbyAudioProcessingEnabled(bool p0);
Will be called when an external application has enables or disabled Dolby Audio processing.  The bool p0 will indicate on (true) or off (false).

void OnDolbyAudioProcessingProfileSelected(DolbyAudioProcessing.PROFILE p0);
Will be called when an external application has selected one of the Dolby Audio processing profiles.

Changing Dolby Audio Profiles

After you’ve called GetDolbyProcessing (…) you can change the Processing mode by calling SetProfile ().  SetProfile takes a PROFILE enum in the DolbyAudioProcessing namespace as an argument and can be one of the following:


if( mDolbyAudioProcessing != null)
    mDolbyAudioProcessing.SetProfile     (DolbyAudioProcessing.PROFILE.Game);

Enabling and Disabling Dolby Audio Processing:

The Dolby Audio processing is a hardware feature of your mobile device, and when enabled, will process all audio playback on your mobile device.

Because of this, you should check and save the state of the Dolby Audio Processing when your application starts, and restore this state when your app or game is pushed to the background.

To enable or disable Dolby Audio Processing, you can directly set the public property Enabled

mDolbyAudioProcessing.enabled = false;

Further Information

Take a look at the two sample projects included with the Java Bindings project.

DolbyTest1 is an example of implementing IOnDolbyAudioProcessingEventListener in the activity.

DolbyText2 uses a separate class for IOnDolbyAudioProcessingEventListener

As well, be sure to take a look at Dolby’s Java documentation included with the API for further details as well as some suggested best practices.

Dolby Audio API Component in the Xamarin Store

If you don’t want to download and build the binding project yourself, there will be a Xamarin component coming soon!