Category Archives: Windows 8

Posts about Windows 8 / 8.1

Nokia Imaging SDK updated

Not surprising news, but worthy of a big mention. The Nokia Imaging SDK has had a new beta release (1.2).

This release brings all the goodness of the Phone library to the new, conjoined Microsoft platform across Windows 8.1 and Windows Phone 8.1. I am hoping to find a little time to play with the new SDK over the next week or so, but the sample apps and code look great. There are also sample apps in the Windows store, although the links in the site seem not to work. I’d suggest opening the Windows Store and searching for “Filter Effects” and installing the one published by Nokia.

It’s //build time!

For those of you who haven’t managed to convince your management to let you go to //build (and this includes me), you can see what you’re missing on the official //build 2014 site. The recordings of the sessions will also be made available there.


Having had a look at the session listings, there is big (although maybe not unexpected) news for Windows Phone and Windows Store apps. As ever, you can find the details 24-48 hours after the live events in the videos and slide decks (or just keep an eye on your favourite Twitter client / blog).

Windows Store Apps with Prism and Unity

It’s been mighty quiet around here. Sorry about that, I’ve been up to my neck in a new project that’s been keeping me pretty busy.

I am going to start a mini-series on developing Windows Store apps using Prism and Unity.

The first of the series (in other words, this post) will look at how to separate your UI and ViewModels into separate projects, but more specifically, how to override the default behaviour to look up the view models from the appropriate place.

By default, Prism will look for your views in the “Views” folder, and take the name of the view (e.g. MainPage.xaml) and use that to look for the ViewModel in the same project’s ViewModels folder. The basics of what it does are to remove the “Page” part from the end of the class name, replace it with ViewModel and look up the class in the x.ViewModels namespace. Of course, if you want to put your ViewModels in another project for maintainability purposes, you’ll need to do a bit of dancing to get it to work.

Thankfully, it’s pretty simple. In your main UI project’s App.xaml.cs, locate the OnInitialise method and add the following code.

Basically, we get the fully qualified name of the target assembly and class type, turn that into a type, and then return it to the view model locator. In the example above, my main UI project is called “MyProject.UI”, and my UI logic (with the view models) is contained in “MyProject.UILogic”.

One thing to notice from my code is that it will also account for namespaced folders beneath the Views folder. The default example implementations don’t take this into account, so the view “Views\Flyouts\AboutPage.xaml” wouldn’t resolve the ViewModel if you follow the same folder structure in the ViewModels folder. Don’t worry, though – as long as you create the same sub-folder structure and have your ViewModels in the correct location, the code above will work.

Don’t forget, though, you’ll need to manage the strings in the snippet above so that they match your assemblies’ fully qualified names. I’ll leave that as an exercise for you, though.

Unit Testing in VS 2013

Visual Studio 2013 now contains functionality to write tests against a Windows Store project. Now, it is a relatively simple task to write unit tests against the code you have in classes within your app’s structure.

A Basic Example

Launch Visual Studio, and from the new project dialog, select Templates -> Visual C# -> Windows Store, and create a new “Blank App (XAML)” named “AppToTest”. Make sure you change the Solution Name value to be “TestableStoreAppExample”


Within the project, create a new folder named “DataAcccess”, and within that a new class named “SampleDataAccess.cs”

Open your newly created class, and mark it as public.

Now we want to add some methods to the class. These will be the methods against which our tests will run, so we will just create some dummy ones for now.

As you can see, the content of the class is very basic at this stage. We will build on this later.

Build the project to ensure that there are no errors.

Next, Let’s add a unit test project.

Right click on the solution in Solution explorer, and click on “Add -> New Project”. In the dialog, select “Unit Test Library (Windows Store Apps”, and name the test project “AppTests”.

In the unit test project you just created, right click on References and select “Add Reference”. In the dialog that appears, navigate to “Solution” on the left hand side, and select “AppToTest on the right, then press OK.

02 - AddReference

Now we can write some tests. For now, I’m just going to add these tests into the default class created when the project was initialised.

Open the file “UnitTest1.cs”

There are couple of annotations to note in this class, but these should be familiar to you if you have used MSTest before.

[TestClass] Marks the class as being a test fixture, containing unit test code.
[TestMethod] Marks a method as being a Unit Test.

For our first test, I’ll re-use the code already in the class. First of all, let’s change the name of TestMethod1 to something more descriptive. Since this test will call the GetSumOfInts method we defined earlier, lets call it TestIntegerSummation().

To break that down, first I create a new instance of the SampleDataAccess class, and call the GetSumOfInts method with 1 and 2, hopefully giving a result of 3. The final lines is where the test comparison happens. In this case, I’m calling Assert.AreEqual to test that the expected value of 3 matches the actual returned value. There are a few other Assert. methods available, e.g. Assert.AreNotEqual, Assert.IsTrue, etc.

Now build the solution in order to make the test available to the test engine.

To run the method, my preferred method is to open the Test menu in Visual Studio, and select Windows -> Test Explorer.


From here you can run all tests, or right click on a test name to run individual ones. (Note, theres another feature that you might want to take advantage of – automatically run tests when you build the solution. To do this, go to Test -> Test Settings and select “Run Tests After Build)

The screenshot above shows that the test we wrote passes.

OK, that’s a synchronous method. What about async ones?

Testing async Methods

This isn’t as intuitive as you might imagine, but once you know the trick, it’s very simple.

As you saw when we created the class to test, I created an async method that goes off and pulls text from a web resource. This is an async call due to the potential delays in loading a web resource.

To create a test for this, we first need to define a new method in the test class and decorate it with the [TestMethod] attribute, then write the code we want to call in the method.

If we do this with the same signature as before, however, the test won’t appear in the test explorer. There are two things we need to do to make the test runnable.

1) Add the async keyword to the method signature (to allow the use of the await keyword in the method call)

2) Change the return type of the test method from void to Task (in the System.Threading.Tasks namespace)

Our method should now look like this.

The test now shows up in Test Explorer and you can run it just like any other method.

More Complex tests

Another great way to test methods is by the use of the [DataTestMethod] attribute. This attribute allows you to specify many sets of data to run in the test, without the need to refactor a test to support different values.

Let’s take our TestIntegerSummation() test and refactor that to support different data sets.

Make a copy of the method, and call it TestIntegerSummationWithData, and add three integer parameters to the signature, calling them “input1”, “input2” and “expectedResult”.

Next we need to update the method body to use these values. The result should look like this.

Change the Attribute from [TestMethod] to [DataTestMethod].

To add sets of data against which we want the tests to run, we can add additional attributes, in this case, the [DataRow()] attribute.

Each DataRow attribute allows you to specify values to be used within the method (in the order they are defined in the method signature). The data we want to pass in should be a reasonable set of data that can be used to test various conditions, but for the purposes of this post, we’ll just pick some random values and test those.

You can see that there are likely to be some edge cases where the calculation will not return the expected result, for example, if we set input1 to be Int.MaxValue. In that case, running the test will show the following in Test Explorer – you can see it gives individual results for each DataRow defined.


There are a couple of ways to handle this situation. We can simple extend the method signature and data rows to pass in a value of whether we expect the test to pass or not

But this isn’t an ideal situation, especially if we expect an exception.

I’ll talk about better ways to handle this in the next post.

Remembering files from outside the application repository

A common scenario for file access in Windows 8 is to allow the user to pick a file from their hard drive, not necessarily from within one of the system-allowable locations such as the local data folder, pictures or documents library, etc. This is, of course, easily achievable using the FileOpenPicker control, but what happens if you want to persist that selection across runs of your app? If you just store a reference to the file location, subsequent runs won’t be granted access to the file and that could bring your app logic crashing down.

The answer is fairly simple. Use the FutureAccessList object in the StorageApplicationPermissions namespace. This allows you to store a file (or folder) along with a token in order to be able to use the IStorageItem later on.

This is a simple example page that uses the FutureAccessList to allow the user to set an image source, which is persisted across runs of the app. For the sake of clarity, I have removed XML comments from the code.



So, what is happening here?

1) In OnNavigatedTo, the app will check to see if we have already set an image file. Let’s assume for now that we haven’t and skip forward.
2) When the user clicks the “Load Image” button, we show a filtered FileOpenPicker to pick a single file. Once we have the file back, we stash it in the FutureAccessList, along with a token to identify the file – in this case, just a string “pickedFileToken”.

3) I have moved the logic to render the file content to the “MyImageWithFileAccess” image out to a separate method. This opens a stream and sets the image source accordingly.
4) On the next run of the app (or visit to the page), we go back in to OnNavigatedTo. This method checks the FutureAccessList to see if we have set an image. In this case, we have, so it retrieves the StorageFile instance from the list and calls the SetImagePath method once more.


  • There is no error handling here – if the user deletes the file, we will get an exception.
  • We are not removing items from the FutureAccessList if we no longer need them. This can be done by calling the Remove method on the list, passing in the token, or clearing the list entirely with the Clear() method.
  • The FutureAccessList can hold up to around 1000 items, but try to use it sparingly. If you are having to keep track of 1000 items, you may need to re-think your app logic.

Syncfusion e-books

Syncfusion have released a series of e-books on various topics, including Windows Store Apps. You need to enter some registration information to be able to access them, but the content looks good at first glance – certainly good enough to make it worth registering.

Unit Testing MVVM Light Messages

MVVM Light has a messenger implementation which can communicate with the UI layers in order to handle things like page navigation, and using this is is very easy to set up a PCL ViewModel assembly to drive both a Windows 8 and Windows Phone app. As a quick example of how you’d set this up, imagione this implementation in a view model.

where NavigationRequestMessage and NavigationTarget are implemented as follows.

Now you can handle the incoming message in your front-end app. In this example, it’s in a Windows 8 Store app.

Note that we unregister the handler again on navigating away from the page, otherwise the message will be handled twice next time we visit the page, three times the next time, etc.)

Now we can write a unit test for this method to ensure that whatever our actual implementation logic tell us should be the resulting navigation is actually correct…

This is a trivial example, but hopefully it explains how to test the navigation in your apps when driven by MVVM Light’s Messenger functionality.

Unit testing gotcha

In the course of writing unit tests on a project, I came across in interesting wrinkle for testing MVVMLight ViewModel classes. When creating a ViewModel, the work is actually done on different thread which leads to the following unit test code throwing an exception.

Instantiating the SummaryViewModel class leads to the following exception message being displayed.

The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))

The solution is relatively simple, though. First I create a method to allow me to run an action and marshal its result back to the appropriate thread.

And then I created a method specifically to create the SummaryViewModel, since I will be doing that many times across my unit tests.

Then it is just a matter of changing my test method to call CreateViewModel and await the result, and all is good.

Extending the platform with ICommands

The ICommand interface has been around for a long time now. It is typically used in a desktop application, for example, to allow the simple binding of buttons or menu items to an action in the code behind, and can be extremely useful.

A common scenario in Windows 8 where command support would be useful is on the click event of a GridView item – for example, an item on your main menu screen. Unfortunately, the platform doesn’t support commands here out of the box, so we have to do some juggling and introduce an attached property to do the work for us.

Let’s start by creating a class to hold the attachable property.

Once we have that set up, we need to define an ICommand in our view model. In this case, I’m using MvvmLight, so I’ll use the RelayCommand type.

Next, we need to wire up the ItemClick event on the GridView (or ListView – both will work with this property)

The last step is to wire up the main page to listen for navigation messages from the ViewModel’s command.

Now, when you run your app, you should be able to navigate to the clicked item (or if you haven’t changed the code, see a MessageDialog with the item id). Note that in the command’s CanExecute method, I only allow navigation to items whose Id is an even number.

GridTapCommand Example (.zip 28kb)


Being a developer in both Windows 8 and Windows Phone is an interesting life. Given the relative newness of both of these platforms, and the similarities in look and feel between them, you’d probably expect that the code can be shared easily between the platforms for the same app. Sadly, that’s not the case for more than about 60% of the code base. (I’m not even going to start on the presentation layer – XAML will always need to be *at least* tweaked to account for the different screen sizes)

The differences between the desktop and phone APIs can cause sleepless nights, as well as necessitating two separate versions of a code base with all the complexities that entails (fixing the same defect multiple times, for example).

Luckily there is a solution that can help us out greatly – Portable Class Libraries. These useful little additions to the platform allow you to write one assembly that can be consumed by Windows 8, Windows Phone, Silverlight or the full .NET framework. But there is a catch – supporting all these platforms comes at a cost of compatibility. The code you write in a WinForms app is likely to use different methods, located in different parts of the BCL to the same feature on the phone.

Fortunately, Microsoft have put a lot of time into portable class libraries, and done some lever under-the-hood work to redirect calls the the PCL versions of some tasks to their platform-specific counterparts. A great example of this is the PCL HttpClient (announcementNuGet package). This makes the task of getting content from the web a snap, and you don’t need to worry about which of the implementations of a web client to use in your assembly. Just use :

Note : If you are targetting .Net 4.0 or Windows Phone 7.x, make sure you also install the Microsoft.Bcl.Async package from NuGet, otherwise the solution won’t build.

So now, all you need to do is call the method as follows, and it will work across all your platforms.

Hopefully that one example will give you some insight into the power of the portable class library, and it’s ability to simplify your coding across the platforms. I will be posting a list of useful NuGet packages that extend the base PCL functionality soon, although there’s plenty of good stuff already in there to get you going.