Enumerating available devices in UWP

In my previous post (Displaying the device picker in a UWP application) I showed how to reuse the UWP device picker flyout within an application.

However, it’s possible that the developer would prefer to offer devices in some alternate UI or, of course, simply locate a known device for an application to use. In the previous post I looked at filtering for Bluetooth devices and those are what I’m after for a little application I’m writing in which I do not require the DevicePicker UI.


Before I get into code to enumerate the devices, I’ll first expand on the lines of code from my previous post, that look like this


Each of the lines like this one actually returns a string which is an Advanced Query Syntax (AQS) language query. So for example this line will produce the following string (formatted to make it more readable)

System.Devices.DevObjectType:=5 AND 
System.Devices.Aep.ProtocolId:=\"{E0CBF06C-CD8B-4647-BB8A-263B43F0F974}\" AND 
(System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#False OR

For completeness, here’s the results of each of the other GetDeviceSelectorFromPairingState calls


System.Devices.DevObjectType:=5 AND 
System.Devices.Aep.ProtocolId:=\"{BB7BB05E-5972-42B5-94FC-76EAA7084D49}\" AND 
(System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#False OR 


System.Devices.DevObjectType:=5 AND 
System.Devices.Aep.ProtocolId:=\"{BB7BB05E-5972-42B5-94FC-76EAA7084D49}\" AND 
(System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#True OR 


System.Devices.DevObjectType:=5 AND 
System.Devices.Aep.ProtocolId:=\"{E0CBF06C-CD8B-4647-BB8A-263B43F0F974}\" AND 
(System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#True OR 

Hence we could now create our own AQS query to search for devices.

See Using Advanced Query Syntax Programmatically for more information on AQS.

Enumerating over devices (simple approach)

A simple approach to enumerating over all the available devices is to use the DeviceInformation.FindAllAsync() method, which is async/await compatible, hence we simply use it like this

var devices = await DeviceInformation.FindAllAsync();

// output all devices
foreach (var device in devices)

Obviously this is a little over the top if we’re looking for a specific device or set of devices. In such cases we can create an AQS query and pass this into one of the FindAllAsync overloads. Hence to recreate my previous post’s query looking for all Bluetooth devices we might prefer to use

var devices = await DeviceInformation.FindAllAsync(

Whilst this solution to the problem of locating devices may fulfil many of the developer’s requirements, an area it fails on is that once the developer has a list of devices they do not have a way to tell when devices are turned off/disabled/or otherwise no longer available. In such situations it’s better to watch for device changes.

Watching for device changes

The DeviceInformation.CreateWatcher method allows the developer to query for devices and via events, watch for items to be added, updated or removed. This would suit an RX type of implementation.

Here’s some code that demonstrates possible usage of the CreateWatcher

   deviceWatcher = DeviceInformation.CreateWatcher(

      deviceWatcher.Added += (watcher, args) =>
         Debug.WriteLine($"Added {args.Name}");
      deviceWatcher.Updated += (watcher, args) =>
         Debug.WriteLine($"Updated {args.Id}");
      deviceWatcher.Removed += (watcher, args) =>
         Debug.WriteLine($"Removed {args.Id}");
      deviceWatcher.EnumerationCompleted += (watcher, args) => 
         Debug.WriteLine("No more devices found"); 
catch (ArgumentException ex)

Again we’re using the AQS created via the GetDeviceSelectoryFromPairingState method and in this simplistic example, we simply subscribe to the Added/Updated/Removed and EnumerationCompleted events to output what devices have been added etc. We also need to be aware of possible ArgumentExceptions, such as incorrectly formatted GUID’s etc. See DeviceInformation Class for a more complete example of this usage.

Displaying the device picker in a UWP application

Developers can use the UWP device picker flyout control within their application to allow the user to select a device from a list of available devices. The list can be filtered to display only particular types of devices.

For example, here’s how to display the DevicePicker flyout without filtering, i.e. showing all available devices

var devicePicker = new DevicePicker();
devicePicker.Show(new Rect(x, y, width, height));

In this case we simply create a DevicePicker and call the Show method which is passed a rectangle where you want the picker to flyout from.

There’s an overload Show method which allows a placement as well.

If you run this code in your application you’ll find that devices are enumerated over and displayed as they are found, so obviously this may take a little bit of time to enumerate all devices.

In most cases we probably want to filter the DevicePicker for a certain type of device. For example if we want to locate all Bluetooth devices we would use the following

var devicePicker = new DevicePicker();


devicePicker.Show(new Rect(x, y, width, height));

In this case we’ve filtered the DevicePicker so it will only display BluetoothLE devices and Bluetooth devices both in a paired (the true parameter) or unpaired (the false parameter).

Obviously we’re going to want to get at the device information or the selected device, when using the Show method, we will need to subscribe to the DevicePicker’s DeviceSelected event, for example

devicePicker.DeviceSelected += (picker, args) =>
   // outputs the selected device name

We can also respond to a couple of other events such as the DevicePickerDismissed and DisconnectButtonClicked.

As an alternate to the event approach, we could switch from using the Show method to use the async/await implementation which combines the Show and the DeviceSelected into he PickSingleDeviceAsync method, i.e.

var device = await 
      new Rect(x, y, width, height));
// outputs the selected device name

IValueConverter.Convert return values

I was updating some value converters in my converters GitHub repos. PutridParrot.Presentation.Converters and realised I had been returning a null in situations where I really should have been returning DependencyProperty.UnsetValue.

Generally we’ll either return a valid value from a converter or one of the following

  • null
  • DependencyProperty.UnsetValue
  • Binding.DoNothing
  • The original value

The documentation (see References) states that when a null is returned then a “valid null value is used”.

However we may actually prefer that the FallbackValue is used (if supplied) instead, hence we can return a DependencyProperty.UnsetValue.

In cases where we neither want a value returned and do not want the FallbackValue to be called, then we return the Binding.DoNothing.

Obviously, in situations where you do not know what to do with a binding value, it might be better to simply return the value passed into the Convert method.


IValueConverter.Convert(Object, Type, Object, CultureInfo) Method

Creating a Prism.DryIoc.Forms application from scratch

I must have created my last Prism.DryIoc.Forms application using a project template but this time created a standard Xamarin.Forms application and then realised I wanted/meant to use DryIoc.

So here’s the steps to turn my “standard” Xamarin.Forms application into a Prism.DryIoc.Forms application.

  • Add the Prism.DryIoc.Forms nuget package to your application
  • Delete the MainPage.xaml files generated by Xamarin.Forms
  • Change the App.xaml to use PrismApplication i.e.
    <?xml version="1.0" encoding="utf-8" ?>
  • Change the App.xaml.cs to derive from PrismApplication, for example
    public partial class App : PrismApplication
  • Remove/replace the App constructor with the following
    public App() :
       this(null) { }
    public App(IPlatformInitializer initializer) :
       base(initializer) { }
  • Now override the OnInitialized method and put the IntitializeComponent call within this, i.e.
    protected override async void OnInitialized()
  • Add folders to the solution named ViewModels and Views
  • Within the Views folder add a MainPage.xaml Xamarin.Forms ContentPage (or page type as required)
  • To register our MainPage and the NavigationPage go back to the App.xaml.cs and add the following method
    protected override void RegisterTypes(IContainerRegistry containerRegistry)
  • Finally, in the App.xaml.cs within the OnIntialized method we’ll navigate to the new page. As the NavigateAsync returns a Task, we can await it so we’ll add async to the OnInitialized method – here’s what that will look like
    protected override async void OnInitialized()
       await NavigationService.NavigateAsync("NavigationPage/MainPage");

Now place any further page’s within the Views folder and add to the RegisterTypes method (if required) and add any view models to the ViewModels folder deriving from BindableBase (if you want to use the Prism MVVM base class).

pre-commit hooks in git

I’ve covered Creating a pre-commit hook for TortoiseSvn previously for SVN. We can create similar hooks for GIT also.

Either create a script or other form of executable (this one’s a C# console application). This example is going to do nothing of real interest. It’ll simply stop commits to a repo. but is useful if we place a Debugger.Break before the Console line, for debugging purposes

static int Main(string[] args)
   Console.Error.WriteLine("No commits allowed");
   return 1;

A non-zero return value indicates a failure and hence this code will effectively stop any commits to the repository it’s applied to.

The arguments sent to the method will be as follows

* 1st arg is the file name of a file which contains a list of files that have changed
* 2nd arg is the file name of a file which has the commit message
* 3rd arg is the folder being committed

Now we compile our application and place it in the .git\hooks\ folder and we need to name it pre-commit.exe.

That’s all there is to it.

Singletons using C# 6 syntax

A while back I wrote the post The Singleton Pattern in C# and just thought it’d be nice to use C# 6 syntax to update this post.

So here’s the code with the change for to use default property syntax

public sealed class Singleton
public static Singleton Instance { get; } = new Singleton();

static Singleton() { }
private Singleton() { }

Advanced Git CLI

Having covered the “basic” commands in my previous post, I wanted to look at some of the more advanced stuff. I’m basically meaning things we probably won’t use as regularly as the previous post’s commands.


Rebasing isn’t necessarily advanced in it’s basic form but I’ve not had any real use for it so far apart from in more complicated scenarios.

Rebasing allows us to apply commits from, for example one branch, onto another branch. For example, let’s say we created a branch off of the wrong branch and so want to move commits from the incorrect branch onto the other branch.

So let’s assume we have feature/mybranch and we need to rebase it onto correct_branch, then we use

git rebase --onto correct_branch feature/mybranch 
git force push

Staging parts of a file

Git allows us to stage whole files/folders as well as parts of a file. For example, maybe we’ve made several changes, but we currently only want to stage a subset of these changes. We can use

git add --patch filename

// or short form

git add --p filename

We’ll now be presented with a list of the new lines and a lot of options. Selecting ? will list what each of the options means.

We can use commands such as e to edit the patch diff file, allowing us to delete lines etc. that are to be staged.

I’ll be adding further “advanced” situations/commands and when I need them.

Using GIT from the CLI

Whilst I use GUI tools, such as the Visual Studio GIT tooling, TortoiseGit etc. I really wanted to get a good understanding on using GIT from the command line. I’ve heard it said that this is the best way to use GIT – whilst I’ll leave that to the reader to decide, let’s get to grips with common tasks etc. from the CLI.

Note: This is not meant to be a comprehensive list of all commands or even all options in the commands I’ve listed. It’s more a list of commands I use often use.

Creating our repository

As you probably know, git is a distributed source control system, so we can create a repository locally (as opposed to requiring a server to host our source code). This means we can create a repository for anything we do, allowing us to commit changes/revert etc.

To create a repository, first create a folder for your files (if you’ve not already done so) then run the following command to create the repository (which will add the .git folder)

git init

This can be run against an empty folder or one with files within it. It will not delete any existing files.

If we want to create a repository that can act as a remote or shared repository we’d use

git init --bare

This remote type of repository is useful in team situations and is special in that no code changes will occur against this repository, it just acts as the PUSH location for each user’s repository.

Staging files

After we’ve add our files or folders we’ll want to stage the files/folders. This step doesn’t always exist in the UI tools (or not in a separate step), but allows us to in essence state what files/folders are to be part of the commit at the specific moment in time. Changes are not committed to the repository and hence changes can be lost. To add all files/folders we can execute

git add .

To add individual files we list each one after the other.

Once staged, we could edit our files further and these changes will not be committed until they too are staged. So think of staging as copying the state of the file/folders at a point in time, ready for committing.

We would tend to stage changes to create a change-set of files, i.e. for a feature or functionality as a single commit.

Unstaging files

To unstage, we simply use

git rm --cached -r .

We replace the . with any specific files that we want to unstage, in such situations the -r can be omitted, i.e.

git rm --cached file1.txt


To find the state of the git repository, including which files are tracked, untracked etc. can be found using

git status

Committing files

When we’re ready to commit our staged files/folders, we execute

git commit

The editor associated with git (for example vi) will be displayed if you run this command and we can now enter a message to differentiate our commit. To commit with a message (i.e. without having to open an editor) simply type

git commit -m "Your message goes here"

Obviously replacing what’s in the speech marks with the log message you want for the commit.

If we want to stage & commit (at least stage files that are already added to the repo.) we can use the -a parameter, i.e.

git commit -a -m "Your message goes here"

Commits are not associated with an incremented number, such as SVN but instead using an SHA1 string. This is a bit of a pain in some ways, especially if, like me, you use the SVN commit number as part of your versioning system, i.e. 1.0.1234 would be the commit 1234 in SVN.

Viewing the log

We can look at the log of commits (i.e. the commit it’s SHA1 and the log message) using

git log

When the : or (END) appears, press q to quit, space bar to continue when you see a :

The log command, by default, is quite verbose, we can reduce this verbosity using

git log --oneline

Which, as the parameter suggests, outputs the logs to a single line, this means only the first 7 characters for the SHA1 string and also a single line from the commit.


To view the current list of branches we use

git branch

Master is the default branch, equivalent to trunk in SVN etc. So if you’ve not yet created any branches you’ll see only master listed.

To create a new branch off of master we use

git branch branch_name

Obviously replacing branch_name with the name of your branch. Whatever branch we’re in when we create a new branch is taken from the current branch. In other words if you’re in master (usually denoted by the name master in the command prompt, if your prompt is setup) then creating a branch from this will branch master.

Checking out a branch

Switching to a branch is known as checking out a branch. So let’s assume we created a branch named rc1.0 from master, we can checkout (or switch) to this branch using

git checkout rc1.0

All of this happens on your local machine (unless you’re also linked to a remote repo.) so you can create branches cheaply and easily to work on locally. When linked to a remote repo. you can push and pull changes to that repo. to add your branches etc.

We can delete a branch using

git checkout -d rc1.0

If there are changes within the branch you’ll need to use the capitalized version of this parameter, i.e.

git checkout -D rc1.0

Tags are branches

A tag is just a branch which has a special meaning in GIT (which, if I recall is the same in SVN). All we’re really doing with a tag is creating a pointer/reference to a commit and in most cases versioning this in some way (at least conceptually).

So using

git tag -a v1.0

will result in a new tag added and named v1.0, we can list the tags by using

git tag

and delete using

git tag -d v1.0


Whether you pull changes from a remote repo. or you are simply working on multiple branches and wish to merge changes between them, you use

git merge branch_name

If there are conflicts then you’ll need to resolve those. This is where one of the diff tools that come with git GUI’s is useful, or use your preferred editor.

GIT will be in a merging state. Make your changes such as resolving conflicts etc., then stage and commit your changes.

Cherry picking the commits you want

Occasionally you’ll be in a situation where, maybe you’ve been working on a branch and somebody says, “we need feature X in master” but you’ve made other changes which you do not want merged, in such cases we look to cherry pick just the changes we want.

The first thing we’d need to do, is view the logs of what’s been committed to look for the commit SHA1 code as these are what we’ll need to tell the cherry-pick command what commits to “merge” into our branch. We do not need to switch to the branch we can run

git log branch_name

to get the log for the specified branch.

Now we run

git cherry-pick sha1_string

where the sha1_string is the commit SHA1 – you need not list the whole SHA1 but usually 4 characters, if unique, will suffice, in other words we need to use enough characters to be unique. We do not need to specify the branch as git will figure this out. Conflicts will still need to be resolved, like any merge. If no conflicts exist then the changes are auto-committed, otherwise you’ll need to add and then run

git cherry-pick --continue

Cloning a repository

When taking a copy of a repository, whether from a remote location such as GitHub or cloning a local repository we use the clone command, i.e.

git clone /c/Development/myapp

In this example I’m using git bash to clone from my c:\Development\MyApp repository into the currently selected folder.

Fetch and Pull

After we clone a repository, whether remote or local, we can fetch or pull as well as push to the other repository. This is all part of a distributed source control system.

To fetch changes from a repository we can use

git fetch

and to pull from our remote repository we use

git pull

Both fetch and pull update our local repository. However pull, in essence does a fetch then merge. So the main difference between a fetch and a pull is that a fetch will do an update (in SVN terms) but it doesn’t force you to merge the changes, whereas pull will try to merge changes and hence you may get merge conflicts. Obviously if you’re busy on some work but want to see what’s happening on a remote repo. then you’d just do a fetch.


When changes are made to a local repository and we want to push those to a remote we use

git push

This doesn’t work on our local repository unless it’s been created with the init –bare command.

Adding “remote” repositories

A remote repository, in this instance is any other repository (i.e. it doesn’t have to be in a remote location). If, for example, we created a local repository and then a “remote” using init –bare we need to tell git about the existence of this repository. To do this we use

git remote remote_name url

So for example, we might create a remote named main on our local machine if we wanted, something like this

git remote main /c/Development/mainrepo

Now we can push to the remote using it’s name, i.e.

git push main

If you want to make an upstream/remote location the default (i.e. so you no longer type the remote name) then you can set this using

git push -u remote_name

where remote name in my example is main.

If you need to check the remotes, simply use

git remote -v


Whilst working on a branch, we might need to switch to another branch or maybe we’ve made changes and want to store them for later use, but not commit. In such cases we can stash our code.

git stash push

This command will temporarily store our changes with no name/text associated with them, this is fine if the stash entry is short lived, but it might be better to assign a name or the likes to the stash entry using

git stash push -m "Your name/message"

We can “pop” the changes back into our repo. using

git stash pop

If we have multiple items stashed, we can pop specific one’s using the –index, for example

git stash pop --index 1

We can list everything in the stash using

git stash list


There are several ways we might revert something. We might want to revert our repo. to a previous version, in this case we use the checkout command with the

git checkout 39e5eec

This will result in a detached HEAD, to “rettach” just use

git checkout master

Obviously replace master with your branch name.

If we have changes staged and/or unstaged but want to revert/clear all the changes we can use

git reset --hard

We can revert a commit by using

git revert d9b66e0 

Where the d9b66e0 is the SHA1 commit you wish to revert.

UWP Application’s file restrictions and logging

UWP applications have restricted access to the local file system and this can cause a few issues when using logging frameworks if you’re expecting to write logs to c:\Temp
or %Temp% locations (for example).

Your UWP application can write to the application’s installation folder, for example

var installedLocation = 

another alternatively is application data location, such as

var localFolder = 

// or

var localCache = 

These last two location will translate to a location such as the following, where username is the (as you’d expect) username the user logged into the machine with, and the GUID is the package family name GUID (taken from the application’s manifest). This is actually an extended GUID.


Note: At the time of writing I’m not sure where the string after the underscore which follows the GUID comes from.

Let’s take a quick look at using Serilog’s File Sink to write our log files. Using NuGet install Serilog and Serilog.Sink.File and use the following code

Log.Logger = _logger = new LoggerConfiguration()
      new JsonFormatter(renderMessage: true),
      ApplicationData.Current.LocalCacheFolder.Path + "\\log.txt", 
      rollingInterval: RollingInterval.Minute)


File access permissions

OnIdiom and OnPlatform

When developing a Xamarin Forms cross platform application, we’ll have a shared library where (hopefully) the bulk of our code will go, be it C# or XAML.

However we may still need to make platform specific changes to our XAML, whether it’s images, margins, padding etc. Along with the possible differences per platform we also have the added complexity of the idiom, i.e. desktop, phone or tablet (for example) which might require differences, for example maybe we display more controls on a tablet compared to the phone.


We’re still likely to need to handle different platforms within this shared code, for example in Xamarin Forms TabbedPage we used OnPlatform like this

   <OnPlatform x:TypeArguments="FileImageSource">
      <On Platform="iOS" Value="history.png"/>

The above simply declares that on iOS the ContentPage Icon is used and is located in the file history.png.

We can handle more than just images, obviously we might look to handle different margins, fonts etc. depending upon the platform being used.

We can declare values for multiple platforms using comma separated values in the Platform attribute, for example

<OnPlatform x:TypeArguments="FileImageSource">
   <On Platform="iOS, Android" Value="history.png"/>
   <On Platform="UWP" Value="uwphistory.png"/>

OnPlatform’s Platform attribute currently supports iOS, Android, UWP, macOS, GTK, Tizen and WPF.

Ofcourse we can simply use Device.RuntimePatform in code-behind to find out what platform the application is running on if preferred.


Working in much the same was as OnPlatform. OnIdiom is used for handling different XAML or code based upon the current device is classed as a Unsupported, Phone, Tablet, Desktop, TV or Watch.

In XAML we might change the StackLayout orientation, for example

   <OnIdiom x:TypeArguments="StackOrientation">

We can use the Idiom within code-behind by checking the state of Device.Idiom.