Determine if running on Windows Phone from a UAP application

There is new metadata query support in Windows 10 to allow your code to react at runtime based on which APIs are available. For example if running on a phone device you may want to start a call, and offer alternative actions on a desktop PC. The correct way to check the availability is to use the ApiInformation class which has a number of methods which take the string name of the type or method and return a Boolean. Without delving into the question of whether a string is the correct approach lets look at an alternative issue.

You want to determine the device type you are running on – say Windows, Windows Phone, Xbox etc to change the type of content you display. You want this high level information not just to alter screen layout or use a specific API. Each Extension SDK provides the device specific APIs for the target devices. Currently the preview tools ship with Windows Desktop Extension SDK and Windows Mobile Extension SDK. If you look at the Object Browser in Visual Studio you can see that adding each of these adds additional root level entries (like a new DLL) and each named after a Contract which is a type contained within it alongside the associated APIs. So you want to quickly determine if you are running on a “Windows Phone” device you could use the following code:-

bool isPhone = ApiInformation.IsApiContractPresent("Windows.Phone.PhoneContract",1);

It’s not currently clear exactly which contracts will be present on which devices – the APIs provided by the Windows.Phone.PhoneContract lib are all familiar APIs present from previous versions of Windows Phone. Since “Windows Mobile” will also be the SKU used for small tablets it isn’t clear if these will also implement this contract or not. If no extension SDKs are added all UAP apps will support Windows.Foundation.FoundationContract and Windows.Foundation.UniversalApiContract.

Although not a part of the current preview tools one can expect a similar set of contracts for the other flavours of Windows – Xbox, IoT etc

Windows Phone

Background GPS in a Windows Phone 8.1 Windows Runtime App

In Silverlight 8.0 there was a capability to run an application for a period of time after the user switched away to perform continuous GPS tracking for up to a few hours. With the switch to the Windows Runtime there was no direct equivalent of this. I discovered however that because there are differences with what you are allowed to do on Windows Phone versus Windows Store apps with the DeviceUseTrigger you can do something similar.

The GPS device itself doesn’t qualify for use with the trigger but you can use another sensor on the device. Since all Windows Phone devices have an Accelerometer you can use this. The documentation states that you must poll the sensor at least every 5 seconds otherwise it will kill your background process. Since GPS commonly updates once per second you are given the choice of polling with a 1-5 second interval depending on what you need. With a bit of logic you could extend this but you’d still be polling the accelerometer at least once every 5 seconds.

The GPS adaptation is simply to recreate a DeviceUseTrigger based background task – using the official code sample as a base. Then we add a Geolocator and get the position on each call of the handler which is called for each reading. In the attached sample we simply capture the position every 5 seconds and update the application tile. So you’ll need to run the app and pin it to the start page to see it at work.

In order to show the minimal code to demonstrate the technique I’ve not added any decent error handling or analytics so don’t just paste this code into a real project and use it as-is.

Sample: BackgroundGps.WinRT


Moving Forwards: Geolocation

Recently I open-sourced a number of Compact Framework projects and when I was working on re-writing an application which used them as a Windows Runtime app I started to think about how much of the code might be useful for app projects. Obviously the API surface for Windows Runtime is totally different to the .NET Compact Framework. In some cases functionality which I wrote is built into the runtime, in other cases I’d made use of P/Invoke to call native APIs which is not an option. However one thing I noticed was that the Windows.Devices.Geolocation namespace which supersedes System.Device.Location was missing one key feature – a built in method to determine the distance between two points. Since I had code for this which was using the same method as the .NET framework I thought this was a prime candidate for migration.

The Windows Runtime is a rather more complex API and whereas .NET had a single GeoCoordinate type the runtime has BasicGeoposition (containing raw latitude, longitude etc) and a number of other types – Geocoodinate, Geocircle, Geopoint etc I decided to first implement an extension method which would work with two BasicGeopositions and then as a helper added an extension method for Geocoordinate which used the logic from the first.

The methods now live in a new NuGet package currently supporting Windows 8.1 and Windows Phone 8.1 – Charming Geolocation and the code will be available in the Charming project. Just add:-

using InTheHand.Devices.Geolocation;

and you can use the GetDistanceTo methods.

Part of the project using this code required an iOS implementation too for which I’ve used Xamarin. Anyone who has used this will know that while the location functionality is similar to what we are familiar with on Windows the API is significantly different. Because I wanted to fix that just the once too I wrote a wrapper API to expose the Windows API wrapping all the CoreLocation stuff. I’ll be adding this library to the NuGet package shortly and am also in the process of moving all the Charming code from CodePlex to GitHub too.

Windows Phone Windows Store

WinRT Background Task Processes

I’ve been working on a Windows Phone 8.1 project which has several background tasks. One of these uses the device’s sensors – using a DeviceUseTrigger. This is different to how a regular periodic task works because the task implementation creates a deferral and keeps running handling the event generated by the sensor device until it is explicitly cancelled. The task is created normally with a class implementing IBackgroundTask and runs under the context of BackgroundTaskHost.exe. Because I wanted to share some data with the other tasks as a when they run I was interested if these other IBackgroundTask implementations were also hosted in the same process. If so this means that any static instances would be shared between them. Since I couldn’t find the answer I did some testing with some additional debugging and discovered that no, they each run in a separate process.

This lead me to explore how to share data between them. There are no built in IPC classes in the Windows Runtime like MessageQueues or similar so really the only options are the LocalSettings for individual setting values and files placed in the LocalFolder for any other data. The added complication here is that you have to handle the situation where both processes may try to read/write the file at the same time. Luckily you can use a named Mutex to enforce exclusive access to the file and have the other process wait on the Mutex.


Calendar Import Now Universal

In order to extend the app onto Windows devices I’ve re-written the Calendar Import app as a Universal app with separate UI and features for Windows 8.1 and Windows Phone 8.1. Both apps add the new feature of browsing for files to import from directly within the app itself. This is on top of the existing filetype support which means you can import an item directly from your Email attachments, Web Browser, NFC, Bluetooth etc

Switching to a Windows Phone 8.1 project also means there are other new features we can support in upcoming releases. Users with a Windows Phone 8.0 device will continue to receive the 1.8 version until their device is updated to 8.1.


Windows Phone

ProgressRing for Windows Phone updated

Last month I posted the latest “charming” helper for Windows development which is a Windows Phone (8.0 or Silverlight 8.1) ProgressRing with the same appearance as its big Windows counterpart.

Today I’ve just pushed an update to NuGet which improves the flexibility of the control by allowing you to override the Foreground colour of the rotating dots. The default is still to use the phone’s accent colour so this is what you’ll see if you don’t specify the Foreground brush explicitly. Details here:-

Windows Phone

Charming Share now “lights up” on Windows Phone 8.1

Charming Share provides a share API for Windows Phone 8.0 projects which mimics the built in support in various system apps and exposes an API which is the same as that available in Windows 8.1 and Windows Phone 8.1. Now that we have a full Sharing feature in Windows Phone 8.1 we can take advantage of this from both AppX and Silverlight 8.1 projects. But what if you need to continue using a Silverlight 8.0 project?

Well the answer is to use Charming Share as it is now smart enough to determine when it is running on an 8.1 device and defer to the system Sharing feature. To quickly illustrate here are screenshots from the same 8.0 project running on both 8.0 and 8.1:-

Charming Share on Windows Phone 8 Charming Share on Windows Phone 8.1

The eagle-eyed amongst you will notice the 8.1 list is quite sparse – this is because it’s taken from the Emulator which has no email accounts or social apps installed. But imagine Facebook etc and any other third-party apps appearing in this list.

In terms of look and feel, I don’t have any plans to change the look of the 8.0 sharing screens – these are designed to match the system as this is how the sharing features appear in Windows Phone 8.

Now that there are so many platforms to cover I’ve changed the main documentation page into a feature matrix so it is easier to compare functionality across platforms and app models


Windows Phone

Silverlight 8.1 Developers – Know Your Manifests!

I’m just passing this on because I’ve been stung by a couple of gotchas introduced with SL8.1 which only seem obvious after you’ve fixed them:-

If your application implements a custom Uri scheme you probably think you just have to add it to your WMAppManifest.xml as you always used to and the job is done. Well no, you see Silverlight 8.1 apps have two manifests – they also have a Windows Store Package.appxmanifest and this is the one the store uses. So if you have an app which handles say “myapp:” and you run an app which calls this Uri the store opens on the phone and displays no results. If you have the app installed then the association works as expected. You need to add the protocol to the Declarations tab of the Package.appxmanifest editor and submit an update. Once this is submitted it starts working even before your new version is necessarily available…

This leads onto the second issue. I always use the WMAppManifest.xml version and increment it and store it in source control. When I submit an 8.0 update I find it frustrating that the store doesn’t pick this up and I have to manually input it. If they don’t match my update prompter gets very confused (but that’s another issue). When I submitted a new SL8.1 app I was impressed that this version box is now greyed out and will populate the value from my submitted package. What I failed to notice when doing an update was that I now need to make sure I update both the WMAppManifest.xml and the Package.appxmanifest versions to keep these in step as the store uses the value from Package.appxmanifest…

Windows Phone

WebAuthenticationBroker for Windows Phone Silverlight 8.x

In Windows Phone 8.1 both the Silverlight and Windows App programming models introduce the WebAuthenticationBroker class. This is inherited from “big” windows but with a change to reflect differences in the app model. Rather than operate as an asynchronous method within the context of your app there is instead an AuthenticateAndContinue method. This closes your app and launches the authentication window in a separate process, returning to your app upon completion. You will find that AuthenticateAsync will throw an exception even though the method is in intellisense and not marked as obsolete. You then need to hook the ContractActivated event of your application instance to determine the result when your application is relaunched. This flow is used not just by the WebAuthenticationBroker but also file pickers and other contract operations.

In Windows Phone 8.0 projects I built my own WebAuthenticationBroker to match the desktop API and with the release of Windows Phone 8.1 I tweaked the look slightly to match and released it as part of the Charming Apps for Windows Phone project. You’ll find this in NuGet here. You can then add OAuth with a couple of lines of code e.g.:-

WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, requestUri, callbackUri);
if (result.ResponseStatus == WebAuthenticationStatus.Success)
   // parse the token here (implementation specific)

The dialog displays the app name and uses as much space as possible for the web content:-


Some caveats – I’ve only used it with a couple of OAuth providers so I can’t guarantee it will support every variation. As with the Microsoft implementations you still have to do some manual parsing of the returned data to get your token. It doesn’t support WebAuthenticationOptions (other than None) and doesn’t read the HTML meta-tags Microsoft introduced to display a logo or background colour. It will however use the app logo and title as the built-in component does on 8.1.

While this does support 8.1 I would suggest that if you are starting a new project you use the built in component and ContractActivated event, if you want to target both 8.0 and 8.1 then you can use this component and the user experience is consistent with the built-in experience.