Category Archives: XAML

(Universal Windows apps)^2

The great majority of apps built for Windows 8.1/Windows Phone 8.1 work on Windows 10 as-is – no changes required what so ever. But what if you want to leverage the new APIs provided by Windows 10 such as the inking API while still supporting the Windows 8.1 version of your app? Or you might be among the few unfortunate ones who have been using some API deprecated on Windows 10; UserInformation class no longer works on Windows 10 but you have to use the User class instead. How to do that without duplicating the code base and having two completely separate app projects to maintain? In this article I’ll describe two approaches to do that.

Shared code and assets in portable project

The first approach is to include all the shared code (in practice that can be almost all of your code) to a separate portable project in your Windows 8.1 solution. First you need to create the project: Right click your solution in the solution explorer, hover on Add and select New Project…

Adding a new project to a solution

Use Class Library as the project type, name it and hit OK.

Creating a class library project

Drag all the code and asset files you want to share between both the Windows 8.1 and Windows 10 app to the newly created Class Library project.

Note that if you have a solution that supports both Windows 8.1 and Windows Phone 8.1, you have to have at least a partial main page (the page you navigate to in the start-up) in the original Windows 8.1 and Windows Phone 8.1 projects. This due to the fact that you can’t add a reference to your Class Library project in the Shared (Windows 8.1/Windows Phone 8.1) project where your App class lives. And without the reference you can’t make your app to navigate to a page defined in your Class Library project in the start-up. Makes sense? Ok, cool, let’s carry on…

Now that we have the code moved to the Class Library project, we must add it as a reference to the other projects so that we can access the classes and assets. Right click the References under the projects in the solution explorer and select Add Reference…

Adding references to a project

On Projects tab you should now find the Class Library project. Check the checkbox and click OK.

Adding a project in the solution to another as a reference

Now fix any minor problems you may have and once your app builds and runs it is time to move on to work on the Windows 10 solution. Create a new Universal Windows 10 application project and add the Class Library project containing the shared code to the Windows 10 solution as an existing project:

Adding an existing project to a solution

Add the Class Library project as a reference to your main Windows 10 project (as explained before), make your main project to use the shared code and you’re all set! Fine – I realize it’s not often this simple and you need to do some tweaking to get all the other dependencies working and so on, but these are the first steps to take.

If you now want to extend the app on Windows 10 by utilizing the cool new APIs, you need to add that specific code to the main project. You can’t, of course, access the code in the main project from the shared code (for many reasons, one being that this would create a circular dependency), but one solution is to define interfaces in the shared code and providing the implementations from the main project. See my example, namely IUserInformationHelper interface in the Class Library, Windows 10 UserInformationHelper implementation and App.xaml.cs where the implementation is provided.

Pros

  • Allows management of the shared code as a single project

Cons

  • Other dependencies (Nuget packages and such) may cause problems e.g. if they aren’t as universal and work only on Windows 8.1 and not on Windows 10
  • You cannot use conditional preprocessing blocks in the shared code (#if) to target a specific platform since the compilation symbols are also shared
Conditional compilation symbols in project preferences (WINDOWS_UWP is for Windows 10 apps)

Shared code and asset files as links

Another way of sharing code between solutions is adding the code and asset files as links. Using links you don’t have to change your existing solution. Simply create a new – in this case – Windows 10 application project and start adding the files from your existing Windows 8.1 solution. Right click your new project in the solution explorer, hover on Add and select Existing Item… Then browse the Windows 8.1 solution folder containing the files you want to add, select the files and click Add As Link:

Adding files as links

The files are now shown in your solution explorer. However, they are not physically in your new project but exist in the Windows 8.1 application project folder. Any changes you make to these files will also appear in both projects.

While adding the files individually can be tedious, the benefit here is that you can take advantage of conditional preprocessing blocks in C# code:

#if WINDOWS_UWP
    // Have your Windows 10 specific code here
#else
    // Have your Windows 8.1 specific code here
#endif

Pros

  • Conditional preprocessing blocks and compilation symbols can be used
  • Dependencies to additional libraries and Nuget packages are easier to maintain
  • Adding platform specific features, e.g. new Windows 10 APIs, is trivial

Cons

  • Adding/removing shared code and asset files needs to be done in both solutions separately

Sample code

An example for using the both approaches featured in this article can be found here in GitHub.

 

Working with Conspicuous Devices (My One Obligatory IoT Article)

IoT! The new, hip word meaning “Internet of Things” – unlike many other trends that come and go, this one is here to stay. Oh, and grow! But enough of the hyped marketing talk; I’m not good at that anyways. What I want to offer to you, developers, in this short blog post, is a small part of Windows 10 offering for IoT related app development, specifically for Bluetooth LE (BLE) beacons.

What is a BLE beacon you ask? It’s a small piece of hardware, typically run by a small battery of which lifetime varies from months to many years. It does but one thing: Transmits a signal with a small payload over and over again (hence the name beacon). Beacons can be attached in many places, both stationary and mobile. Who knows – you could have one in your pants right now!

So, a beacon alone does not do anything useful, but think of what devices receiving the signals can do! Like the whole field of IoT, it’s hard to foresee all the use cases random tech enthusiasts devise with beacons and similar devices. I already worked with one of the visionaries in the field, a company called Sensorberg, and it’s hard not to get excited by their enthusiasm alone.

But, let’s cut to the chase (I promised this would be a short article)!

Windows 10 and its new converged Bluetooth stack

Windows 8.1 did not have enablers for developers to work with beacons, but this unfortunate shortcoming is spectacularly fixed in the spanking new Windows 10. Not only that, but the whole Bluetooth stack is now converged i.e. it’s the same on all devices running Windows 10. However, you should note that some of the features have hardware dependencies, which you have to take into consideration when developing universal apps. The good news is that the same code works everywhere; you just have to catch the possible exceptions in the case of missing hardware support.

The new namespaces for working with beacons are Windows.Devices.Bluetooth.Advertisement and Windows.Devices.Bluetooth.Background. The aforementioned is the one I’ll be focusing in this article. The latter provides the means to work with beacons using a background task.

Implementing a tricorder

What does it take to make your Windows 10 device to scan for beacons. Not much. You simply construct a BLE advertisement watcher instance, give it some filters, start it and wait for beacons to come in range. Then, simply catch the event and do something with the data you received.

DataTricorder“Look Geordi! I received a coupon code!”

In code setting the watcher up and starting it is done like this (based on the snippet taken from the official Microsoft sample):

BluetoothLEAdvertisementWatcher watcher =
    new BluetoothLEAdvertisementWatcher();

var manufacturerData = new BluetoothLEManufacturerData();

// Then, set the company ID for the manufacturer data.
// Here we picked an unused value: 0xFFFE
manufacturerData.CompanyId = 0xFFFE;

// Finally set the data payload within the manufacturer-specific section
// Here, use a 16-bit UUID: 0x1234 -> {0x34, 0x12} (little-endian)
var writer = new DataWriter();
writer.WriteUInt16(0x1234);

// Make sure that the buffer length can fit within an advertisement payload.
// Otherwise you will get an exception.
manufacturerData.Data = writer.DetachBuffer();

// Add the manufacturer data to the advertisement filter on the watcher:
watcher.AdvertisementFilter.Advertisement.ManufacturerData.Add(manufacturerData);

watcher.Start();

To catch the received beacon data you must hook to BluetoothLEAdvertisementWatcher.Received event, where you get the data encapsulated in BluetoothLEAdvertisementReceivedEventArgs. You will find all the data transmitted there as raw byte array and some of the data is provided as properties for convenience. You can check out the format of the beacon data here.

If at this point you are too eager to jump right into code, I don’t mind. You can check out the official Microsoft sample code here or take a look at my awesome sample here.

Your device can be a beacon too

Windows 10 also allows you to make your device function as a beacon (and remember that Windows 10 runs on all kinds of devices including even the smallest ones). This is handy for a number of reasons, probably many use cases exist that I can’t even imagine yet, but of course, the obvious one is testing your app – unlike a standard, physical beacon, the beacon ID, used to identify a certain beacon, can be changed dynamically and you can easily start or stop broadcasting with a push of a button.

For turning your device into beacon there’s a class called BluetoothLEAdvertisementPublisher. The use of it is just as simple as that of the watcher; construct the instance, give it a payload and hit start! Here’s an example (based on the snippet taken from the official Microsoft sample):

// Create and initialize a new publisher instance.
BluetoothLEAdvertisementPublisher publisher =
    new BluetoothLEAdvertisementPublisher();

// We need to add some payload to the advertisement. A publisher without any payload
// or with invalid ones cannot be started. We only need to configure the payload once
// for any publisher.

// Add a manufacturer-specific section:
// First, let create a manufacturer data section
var manufacturerData = new BluetoothLEManufacturerData();

// Then, set the company ID for the manufacturer data. Here we picked an unused value: 0xFFFE
manufacturerData.CompanyId = 0xFFFE;

// Finally set the data payload within the manufacturer-specific section
// Here, use a 16-bit UUID: 0x1234 -> {0x34, 0x12} (little-endian)
var writer = new DataWriter();
UInt16 uuidData = 0x1234;
writer.WriteUInt16(uuidData);

// Make sure that the buffer length can fit within an advertisement payload. Otherwise you will get an exception.
manufacturerData.Data = writer.DetachBuffer();

// Add the manufacturer data to the advertisement publisher:
publisher.Advertisement.ManufacturerData.Add(manufacturerData);

publisher.Start();

Note that the advertising feature is a limited hardware resource, which can be used by multiple apps. So, unless your app is the only one using it on your device, be prepared for having to wait for the resource to be available. Luckily, you can hook to BluetoothLEAdvertisementPublisher.StatusChanged event. One of the statuses is “Waiting”.

 

Please, have my code

Screenshot of BLE Beacon Sample

You can check out my BLE beacon sample, which does both scanning (using the watcher) and advertising (using the publisher). It allows you to enter the desired beacon IDs. I tried to keep the code as simple as I could by adding two utility classes: Beacon and BeaconFactory. The sample is hosted in GitHub here.

Wait, there’s more…

You might have noticed that I did not cover beacon scanning scenario where the application is in the background. That’s because my dear colleague, Juhana Koski, has already covered that in his article, and it also comes with a code sample.

Do also check out this great session on BLE advertisement APIs from the 2015 //build/ conference.

Finally, for a proper developer, which I’m sure you are, code speaks more than… umm… 1000 words which are not code. Thus, check these samples to get a quick dive-in to the world of BLE beacons on Windows 10 universal platform:

Staying in control

When working on an app even a bit more complex than couple of views, you quickly find yourself in a need to create either a custom UI components (user controls in Windows development terms) or at very least a composite components. Whenever I find myself in this kind of situation, I try to generalize them and make them as self-contained as possible. In my opinion this approach has two benefits: First, obviously, I can easily use them later in other projects. Second, it makes a better architecture and makes it easier to have more instances of the component in the same project.

I find this to be a standard practice; in most cases when you run into this situation, you find a ready-made solution to your problem in stackoverflow. Usually, it’s in a form of a snippet that you just copy into your project and sometimes you get the complete user control from some project. I recently worked on an app, and found there were no solutions to couple of my problems, so I thought I would fill in the gap and provide them here. Both solutions are quite trivial (except for the first one, if you target a specific platform/framework version), but the thought of saving the precious time of any developer facing the same problem makes me happy.

Sliding panel user control

 

So, to the point. Behold, a sliding panel! With buttons, text, bells and whistles! User can drag it or animate it by tapping an icon or a button. The problem here isn’t the composite nature nor the way it is manipulated (dragging), but the performance when your project is built on a specific framework, namely Windows Phone Silverlight. I try to always work with the latest frameworks, but sometimes it’s just not possible. The performance trick used here is very conventional: Render the whole layout in a bitmap and then animate that. The nice thing about this component is that it works in both Silverlight and Windows Universal apps. It is fully self-contained.

See more detailed description and get the source code from my GitHub project.

Ticker text user control

In image: Three ticker text user controls in StackPanel layout.

This is quite trivial and rarely needed UI component. To be honest, I was quite surprised not to find a version of this anywhere in the interwebs. I suppose one must be somewhere and my search engine skills are just below average. Or it could be that this component is so trivial, that no-one bothers to even look for a ready-made solution. In any case, since I lack all discretion, I dumped my user control here (or actually to GitHub) anyways.

In case the “ticker” does not ring any bells, it’s the component that has a scrolling text on it, much like you see in the lower part on your television sets when watching the news. My control, like the sliding panel, is supported on Windows Silverlight and in Windows Universal apps.

Find the code in GitHub.