Editorial: Why the app gap on Windows Phone/10 Mobile is a bigger problem than I thought

Note: as this is an editorial, this blog post reflects my own experience and thoughts. You will agree with some points, but disagree with others. Feel free to leave a comment to start a discussion below.

Recently, I received a Nexus 5x as development device for a project I am about to start. As tech enthusiast, I could not resist to start using it as my daily driver.

As you might guess, I started with an install orgy of all the apps I am using on my Lumia 950 XL and set them up. It may be surprising, but I immediately recognized huge differences between the platform versions.

Take the Facebook app for example. Animations are smooth like butter, almost all settings are in app instead of leading to a mobile page, even loading content and scrolling is a whole lot better than on Windows 10 Mobile.

Another example is the Path app. Never been updated since its launch on Windows Phone, I was truly surprised when I opened It on Android. It is an app that really is fun to use on Android. I bet they would have a lot more users on Windows if they align the app… sadly, they abanonded the platform completely a few month ago.

The last example is the WordPress app. It exists on Windows (Phone) for existing users, but the experience on Android is galaxies away from the one the one in Windows (Phone) has/had. I am even writting this post with it, because it feels just right to do this (I only did that once on Windows Phone).

These were only three examples, but they show pretty much how different official apps can be between platforms (and how they are supported). And they all show, that Windows really has no priority anywhere (sadly).
The quality of apps that are available on Windows is not all, though. Of course, I downloaded also some apps that aren’t available for my Lumia 950 XL as well. And it does make a difference.

On my Lumia, I often use the mobile page for things to do/achieve. On Android, I have a whole lot more apps to choose from, so I never had to open the browser for:

  • my mobile carrier
  • my landline & tv carrier
  • the communal page of Winterthur (where I live)
  • swiss auction page of ricardo.ch
  • swiss page tutti.ch
  • Amazon (Bonus: the apps are connected, needed to log in only on one and all others had my account)
  • eat.ch, a swiss food order service
  • Imgur
  • Giphy
  • and more…

Some say a good mobile page is as good as an app. That’s wrong for most cases. A good written app is always handier than a website. On any platform (at least in my experience).

Android app quality has improved a lot in the last two and a half years (that’s how long it took me to deeply test the OS and the ecosystem again). They are equal to the high level on iOS (which I saw also recently, as my son broke out of the Windows world I created at home).

On Windows, we have a lot of third party apps that are trying to fill the gap. I respect those developers (at least those that use legal, public APIs), but it is just not the same. And even on Android (or iOS), there is room for third party apps besides the official ones.

The Android OS itself feels also grown up, and it is difficult to say if iOS or Android are better. It is more a question of who you prefer – Google or Apple.

Microsoft’s Windows (Phone/10 Mobile) is on a good way to get on par. Lots of the functionality is also there. But… as long as the provider of a service, no matter which kind, do not use them (for whatever reason), Windows will never grow up. The Universal App approach is a good idea, and it may pay off one day – or it may be too late already. The recent switch to focus on enterprise users does not really help. Because also enterprise users tend to have only one device. And also enterprise users tend to use apps on their mobile device.

As a WinPhan, writting this honest post deeply hurts. Even more, as I really am thinking about switching platforms for mobile things. Not as a developer, but as a user (at least until Windows has grown up).

iconbuttondemostill

[Updated] How to create a pure icon button for your UWP app

[Updated: the first version of this blog post was using a UserControl. Thanks to a discussion on Twitter, I realized that wrapping it into a UserControl is overblown (yes, sometimes I tend to write more code than necessary). This is the updated version using only a Style for the button.]

When writing apps, you often come along a point where you want to style controls differently than the original style. Today, I‘ll show you a pure icon button that does not show the surrounding shape and borders. Instead, it highlights the icon of the button when hovering over it, while it changes the color to the user’s accent color when it gets pressed. Here is a little animation of what I am talking about:cromeless button demo

It all begins with the default style of the Button control, which you can see here. We are going to modify this Style until it matches the above animation. The first thing we change is the BackgroundBrush – set it to ‘Transparent’ to get rid of the grey shape that the button control comes with when hovering over it or pressing it:

<Setter Property="Background" Value="Transparent"/>

As we want an icon button, we need to choose a common source for the icons as well. I am using a Path Shape as the icon source, as it allows modifications to be done in XAML. So the next step is to add a Path shape to the Style:

                            <Path x:Name="PathIcon"
                                  Data="{TemplateBinding Content}"
                                  Stretch="Uniform"
                                  Fill="{TemplateBinding Foreground}"
                                  Stroke="Transparent"
                                  StrokeThickness="1"
                                  Margin="4"
                                  RenderTransformOrigin="0.5,0.5">
                                <Path.RenderTransform>
                                    <TransformGroup>
                                        <TransformGroup.Children>
                                            <RotateTransform Angle="0" />
                                            <ScaleTransform ScaleX="1" ScaleY="1" />
                                        </TransformGroup.Children>
                                    </TransformGroup>
                                </Path.RenderTransform>
                            </Path>

In this case, as we just want to use the icon within our button, we can safely remove the ‘ContentPresenter’ part in the Style. We have made quite some progress already, but that all does not make the control behaving like in the animation yet.

Now it is the time to modify the CommonStates of the Button’s style. Our Button uses only an icon, so we need to add the color states for the Path’s ‘Fill (=Foreground)’ to the states. Here are the modifications:

‘PointerOver’ state:

                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Fill" Storyboard.TargetName="PathIcon">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightBaseHighBrush}"/>
                                            </ObjectAnimationUsingKeyFrames>

‘Pressed’ state:

                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Fill" Storyboard.TargetName="PathIcon">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlForegroundAccentBrush}"/>
                                            </ObjectAnimationUsingKeyFrames>

‘Disabled’ state:

                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Fill" Storyboard.TargetName="PathIcon">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledBaseMediumLowBrush}"/>
                                            </ObjectAnimationUsingKeyFrames>

To get the icon’s outline highlighting, we are going to use the Path’s ‘Stroke (=Border)’ property. Add these modifications to the Style in XAML:

‘PointerOver’ state:

                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Stroke" Storyboard.TargetName="PathIcon">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightAccentBrush}"/>
                                            </ObjectAnimationUsingKeyFrames>

‘Pressed’ state:

                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Stroke" Storyboard.TargetName="PathIcon">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="Transparent"/>
                                            </ObjectAnimationUsingKeyFrames>

‘Disabled’ state:

                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Stroke" Storyboard.TargetName="PathIcon">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="Transparent"/>
                                            </ObjectAnimationUsingKeyFrames>

All that is left is to use the Style on any desired button:

    <Button x:Name="BaseButton" Style="{StaticResource TransparentButtonStyle}"></Button>

If you now use this one in an application, you will get the same result as in the initial animation.

For easier use, here is the complete code:

        <Style x:Key="TransparentPathIconButtonStyle" TargetType="Button">
            <Setter Property="Background" Value="Transparent"/>
            <Setter Property="Foreground" Value="{ThemeResource SystemControlForegroundBaseHighBrush}"/>
            <Setter Property="BorderBrush" Value="{ThemeResource SystemControlForegroundTransparentBrush}"/>
            <Setter Property="BorderThickness" Value="{ThemeResource ButtonBorderThemeThickness}"/>
            <Setter Property="Padding" Value="8,4,8,4"/>
            <Setter Property="HorizontalAlignment" Value="Stretch"/>
            <Setter Property="VerticalAlignment" Value="Stretch"/>
            <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/>
            <Setter Property="FontWeight" Value="Normal"/>
            <Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}"/>
            <Setter Property="UseSystemFocusVisuals" Value="True"/>

            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Grid x:Name="RootGrid" Background="{TemplateBinding Background}">
                            <VisualStateManager.VisualStateGroups>
                                <VisualStateGroup x:Name="CommonStates">
                                    <VisualState x:Name="Normal">
                                        <Storyboard>
                                            <PointerUpThemeAnimation Storyboard.TargetName="RootGrid"/>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="PointerOver">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Stroke" Storyboard.TargetName="PathIcon">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightAccentBrush}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Fill" Storyboard.TargetName="PathIcon">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightBaseHighBrush}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <PointerUpThemeAnimation Storyboard.TargetName="RootGrid"/>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="Pressed">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Fill" Storyboard.TargetName="PathIcon">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlForegroundAccentBrush}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Stroke" Storyboard.TargetName="PathIcon">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="Transparent"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <PointerDownThemeAnimation Storyboard.TargetName="RootGrid"/>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="Disabled">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Fill" Storyboard.TargetName="PathIcon">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledBaseMediumLowBrush}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Stroke" Storyboard.TargetName="PathIcon">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="Transparent"/>
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualState>
                                </VisualStateGroup>
                            </VisualStateManager.VisualStateGroups>

                            <Path x:Name="PathIcon"
                                  Data="{TemplateBinding Content}"
                                  Stretch="Uniform"
                                  Fill="{TemplateBinding Foreground}"
                                  Stroke="Transparent"
                                  StrokeThickness="1"
                                  Margin="4"
                                  RenderTransformOrigin="0.5,0.5">
                                <Path.RenderTransform>
                                    <TransformGroup>
                                        <TransformGroup.Children>
                                            <RotateTransform Angle="0" />
                                            <ScaleTransform ScaleX="1" ScaleY="1" />
                                        </TransformGroup.Children>
                                    </TransformGroup>
                                </Path.RenderTransform>
                            </Path>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

As always, I hope this post is helpful for some of you. If you have questions/ideas for improvements or just want to talk about the control, feel free to leave a comment below.

Happy Coding, everyone!

[Updated] How to create a multi architecture NuGet Package from a UWP class library

Like I already announced in my last blog post about UWP AppServices, I am going to show you how to create a NuGet package for UWP class libraries. I am going to go through the whole process, and provide you the steps I found as easiest (it may be the case that there are other ways for the single steps, too). I am continuing with my AppServices sample to show you all the steps I did.

Preparations

The first step is to download the latest NuGet.exe. This command line application will do all the work that is needed to create the package. Once downloaded, let’s do some modifications to our project.

It is good practice to put all the NuGet stuff into a folder in your project. That’s what we’re doing now, adding a folder named NuGet and put the NuGet.exe file in it (create the folder and copy and paste it in file explorer). The next step we would do now is to open the Package Manager Console in Visual Studio and call the nuget.exe with the parameter ‘spec’ to create a .nuspec file. The.xml formatted .nuspec file describes the structure of the NuGet package.

Because we need a multi architecture package for our Universal class library, I prefer another approach. I created a sample .nuspec file that already describes part of the structure that we need.  After pasting the file in, change the file name to match “[projectname].nuspec”. To add the file to your project in Visual Studio, click on the ‘ Show All Files’ button on top of the Solution Explorer Window. Now you will see the previously added NuGet folder and the .nuspec file. Right click on the renamed .nuspec file and select  ‘Include in Project’:

image

Inside the .nuspec file

Let’s have a look into the .nuspec file. The first part is the ‘metadata’ part, which describes the file’s properties:

    <metadata>
        <id>$title$</id>
        <version>$version$</version>
        <title>Simple Leet AppService Handler</title>
        <authors>$author$</authors>
        <owners>$owner$</owners>
        <requireLicenseAcceptance>false</requireLicenseAcceptance>
        <description>$description$</description>
        <copyright>Copyright ©  2016</copyright>
      
        <dependencies>
        </dependencies>
    </metadata>

Just replace the the $-enclosed variables with your data. The more interesting part in this case is the dependencies part. With the Universal app platform, Microsoft introduced the .NETCore package that provides all the APIs. It is very hard to maintain the dependencies manually. Luckily, there is already a Nuget package that helps us to automate this process: NuSpec Dependency Generator.

Just add the package to your project and compile it. That’s it, you have all the dependencies in your .nuspec file:

    <dependencies>
      <group targetFramework="uap10.0">
        <dependency id="System.Diagnostics.Debug" version="4.0.10" />
        <dependency id="System.Runtime" version="4.0.20" />
        <dependency id="System.Runtime.WindowsRuntime" version="4.0.10" />
        <dependency id="System.Threading.Tasks" version="4.0.10" />
      </group>
    </dependencies>

Now that we have the dependencies in place, we’re ready for the next step: creating the package file structure. As we want a multi architecture package, we need to compile the project for every cpu architecture. This is done pretty simple, just select Release mode and build the project for all architectures:

Screenshot (97)

To check if we have all files in place, just open the corresponding architectures’ folder in the bin folder of your project:

Screenshot (98)

The next part is to add these folders to the .nuspec file within the ‘files’ tag:

  <files>
    <file src="..\bin\ARM\Release\SampleAppServiceConnector.dll" target="runtimes\win10-arm\lib\uap10.0" />
    <file src="..\bin\ARM\Release\SampleAppServiceConnector.pdb" target="runtimes\win10-arm\lib\uap10.0" />
    <file src="..\bin\x64\Release\SampleAppServiceConnector.dll" target="runtimes\win10-x64\lib\uap10.0" />
    <file src="..\bin\x64\Release\SampleAppServiceConnector.pdb" target="runtimes\win10-x64\lib\uap10.0" />
    <file src="..\bin\x86\Release\SampleAppServiceConnector.dll" target="runtimes\win10-x86\lib\uap10.0" />
    <file src="..\bin\x86\Release\SampleAppServiceConnector.pdb" target="runtimes\win10-x86\lib\uap10.0" />
  </files>

Noticed that we use the ‘runtimes’ folder with the corresponding architecture structure folders? This is how we need to set it up for multi architectural packages. Including the .pdb files is always a good practice, even with the missing symbolication in UWP applications (at least for now. I was told from inside Microsoft that they are working on this, but it seems to be a very complicated process for .NET native compiled applications).

Very important: the entry reference

This alone does not work, though. We need a reference that we can use as entry point for our package. To do this, we need to add an additional folder entry to our .nuspec file:

    <file src="..\bin\Release\SampleAppServiceConnector.dll" target="ref\uap10.0" />
    <file src="..\bin\Release\SampleAppServiceConnector.pri" target="ref\uap10.0" />

[Update:] Now that we have added this folder structure to the .nuspec file, the only thing we need to do is add an AnyCPU compiled .dll. Regarding some feedback I received on Twitter, it should work if you compile the library as AnyCPU like a lot of devs are used to. I you do not have success with that like me, you can also convert the x86 .dll into an AnyCPU .dll by removing the 32Bit-flag.  Here is how to do it:

  1. Copy the x86-.dll file  into the Release folder under the bin folder of your project
  2. Copy the x86-.dll and .pri file into the Release folder
  3. open the Visual Studio Developer Command Prompt (type ‘dev’ into the start menu, it will appear there)
  4. type:  corflags.exe /32bitreq- [path to Release folder]\[dll-Name].dll
  5. the result should look like this:Screenshot (101)

If you have additional files like xaml files, you would need to add a new folder in the uap10.0 folder (with the same name that your project has). I’ll update this post and the sample once I have a matching sample at hand.

Creating and testing the package!

Now we are finally able to pack the NuGet package. As we have the Developer Command Prompt already open, lets change the running directory to match the NuGet folder in our project. All we then need to do is to run the pack command of the nuget.exe that we already placed in there:

image

And that’s it. We have our NuGet Package in place. Now let’s test our package, before we are going to upload it to nuget.org. All you need to do is to have a folder for your NuGet packages on your machine. I made a folder called ‘TestNuget’ on mine, and copied the package into it (which is the same as the Nuget push command we’ll see later).

To add this folder as package source, open the ‘Options’ menu in Visual Studio and select ‘Package Sources’ in the NuGet Package Manager entry. Hit the add symbol on top and add your folder:

Screenshot (104)

Now if you open the Package Manager and select your local folder as source, you will be able to install and test your package:

image

Publishing the package to nuget.org (or your NuGet server)

The final step is to publish the newly generated package to nuget.org or your own NuGet server. As we still have the Developer CMD opened, we simply use the following command:

nuget push [path to your package.dll] [nuget.org API Key]

Another alternative would be to use the nuget.org website to upload the package: https://www.nuget.org/packages/upload (the page is self explanatory).

That’s it, your NuGet package is available for all you consider to use it. I also updated the sample of my last blog post on GitHub to include these changes, if you want to play around.

Some of you may go a different route for some steps. I have found this a good way that is also kind of memorable (for me). I would love to hear feedback on this and to discuss this, so feel free to leave me a comment.

Like always, I hope this post is helpful for some of you. Happy coding, everyone!

How to add and consume an AppService to your UWP app (complete walkthrough)

One of the very cool and helpful new features Microsoft added for UWP apps are AppServices. AppServices allow your application to provide functionality to other applications without even being launched. This post shows how to add and consume an AppService.

Creating the AppService

An AppService is a background task that is hosted by your application. To add an AppService to your existing application, right click on the solution name in the Solution Explorer and select ‘add new  project’. Under category Windows\Universal, select ‘Windows Runtime Component’, give it a name and click on ‘OK’:

image

This adds a new project to your solution. Rename or Replace Class1.cs to something that matches your need (in my sample, I just use ‘Handler’). The next step is to implement the IBackgroundTask interface:

image

This will add the ‘Run(IBackgroundTaskInstance taskInstance)’ method to the class. Before we continue with to integrate our AppService further into the system, we need to declare two members in the Handler class:

        private BackgroundTaskDeferral _backgroundTaskDeferral;
        private AppServiceConnection _appServiceConnection;

Now that we have those two in place, let’s have a look inside the Run method:

       public void Run(IBackgroundTaskInstance taskInstance)
        {
            //get the task instance deferral
            this._backgroundTaskDeferral = taskInstance.GetDeferral();

            //hooking up to the Canceled event to close app connection
            taskInstance.Canceled += OnTaskCanceled;

            //getting the AppServiceTriggerDetails and hooking up to the RequestReceived event
            var details = (AppServiceTriggerDetails)taskInstance.TriggerDetails;
            _appServiceConnection = details.AppServiceConnection;
            _appServiceConnection.RequestReceived += OnRequestReceived;
        }

The first step is to get a background task deferral. This allows the service to run asynchronous code against the background Task without crashing. The next step is to handle the background task’s Canceled event. Even if the Task get’s cancelled, we must complete the process and tell the OS that we have finished. If we won’t do this, the AppService will stop working on the first cancel operation. To do so, add this code to your Canceled event handling method:

            this._backgroundTaskDeferral?.Complete();

Last but not least, we need to handle the request that the AppService received. To do so, we need to get the AppServiceTriggerDetails from our BackgroundTask. This allows us to get  a reference to the AppServiceConnection, which provides the event ‘RequestReceived’ that we want to handle.

Within our RequestReceived event handling method, the effective work is done. As this is also an asynchronous action, we first need to get again a reference to the event’s Deferral:

var msgDeferral = args.GetDeferral();

The next step is to get the data from the event’s AppServiceRequestReceivedEventArgs:

            var input = args.Request.Message;

This gives us a ValueSet (which works like a Dictionary), which we need to parse to get the input data we need:

var response = (string) input["question"];

The ValueSet entries you are setting up here are the parameters your consumer has to provide. In my sample, I have only a single parameter called ‘question’, but it works also well with more parameters. After we pulled the parameters out of the ValueSet, we can do the work our AppService is supposed to do.

It is a good practice to separate the function you want to provide in the AppService in a separate project. You need to write the code only once, but can use it in your main application as well as in the AppService. In my Sample, this is done in the AppServiceResponder project. It may look like an overkill in this case, but if you have more complex logic than the sample it will absolutely make sense.

I am wrapping the work into a try/finally block as we need to complete the async operation in any case to keep our AppService running. This way, even if the work is not completed successfully, at least we come out clean of the AppService Task. Within the try part of the try/finally block, we are doing the work that the service is supposed to do. The result needs to be passed as a ValueSet again. To effectively send the result to the requesting app, we use this line of code:

await args.Request.SendResponseAsync(result);

Here is the full method for reference:

        private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            //async operation needs a deferral
            var msgDeferral = args.GetDeferral();


            //picking up the data ValueSet
            var input = args.Request.Message;
            var result = new ValueSet();

            //parsing the ValueSet
            var response = (string) input["question"];

            try
            {
                //as long as the app service connection is established we are using the same instance even if data changes.
                //to avoid crashes, clear the result before getting the new one
                result.Clear();

                if (!string.IsNullOrEmpty(response))
                {
                    var responderResponse = AppServiceResponder.Responder.Instance.GetResponse(response);

                    result.Add("Status", "OK");
                    result.Add("response", responderResponse);
                }

                await args.Request.SendResponseAsync(result);
            }
            //using finally because we need to tell the OS we have finished, no matter of the result
            finally
            {
                msgDeferral?.Complete();
            }
        }

Declaring the App Service in the host app

The final step we need to apply is to declare the AppService in our Package.appxmanifest. Declaring the AppService is pretty simple. Just select ‘App Service’ in the dropdown and hit ‘Add’. Give it a name (Microsoft recommends ‘reverse domain name style ‘,  so I used it. The last step is to declare the Entry point, which is AppServiceNamespace.ClassName (replace with yours).

The result should look like this:

image

Now build the solution. If all is set up correct, you have made an application implementing an AppService.

Creating the AppService Connector

Like I recommend to extract functionality that runs inside the AppService, I do so for the code that connects the app into a separate project. This allows you to reuse the project in multiple apps. An additional advantage is that you can create a Nuget package for this separate project to provide this functionality to other developers (I will write a separate post about this to keep this one focused on the AppService).

After adding a new project to the Solution, rename/replace also here Class1. I named my handler class just Connector. To make it a no brainer to use the connector, I implemented the class as singleton:

        private static Connector _instance;
        public static Connector Instance => _instance ?? (_instance = new Connector());

After that, I added an asynchronous Task that returns the AppService’s response. Let’s have a look inside the task. Inside the using statement for the AppServiceconnection, the first thing we need to do is to call the AppService with these three lines of code:

                //declaring the service and the package family name
                SampleAppServiceConnection.AppServiceName = "com.msiccdev.sampleappservice";

                //this one can be found in the Package.appxmanifest file
                SampleAppServiceConnection.PackageFamilyName = "acc75b1a-8b90-4f18-a2c4-08b0d700f1c6_62er76fr5b6k0";

                //trying to connect to he AppService
                AppServiceConnectionStatus status = await SampleAppServiceConnection.OpenAsync();

We’ll get a AppServiceConnectionStatus back, which helps us to deside how to go on in the task. If we do not have success in getting a connection to the AppService, I am returning an error description. For this, I created a simple helper method:

        private string GetStatusDetail(AppServiceConnectionStatus status)
        {
            var result = "";
            switch (status)
            {
                case AppServiceConnectionStatus.Success:
                    result = "connected";
                    break;
                case AppServiceConnectionStatus.AppNotInstalled:
                    result = "AppServiceSample seems to be not installed";
                    break;
                case AppServiceConnectionStatus.AppUnavailable:
                    result =
                        "App is currently not available (could be running an update or the drive it was installed to is not available)";
                    break;
                case AppServiceConnectionStatus.AppServiceUnavailable:
                    result = "App is installed, but the Service does not respond";
                    break;
                case AppServiceConnectionStatus.Unknown:
                    result = "Unknown error with the AppService";
                    break;
            }

            return result;
        }

For the case we are successful with our connection attempt , I am sending the needed ValueSet with these lines:

                    var input = new ValueSet() {{"question", question}};
                    AppServiceResponse response = await SampleAppServiceConnection.SendMessageAsync(input);

I am using a simple ValueSet with just one value here, but I have already done it with a more complex structure and this works as well. I haven’t reached any limits by now, but I think that they are the same as for all Background Tasks (don’t throw stones at me if it is different). The only thing I then need to do is to handle the response according to its status with this switch statement:

                    switch (response.Status)
                    {
                        case AppServiceResponseStatus.Success:
                            result = (string) response.Message["response"];
                            break;
                        case AppServiceResponseStatus.Failure:
                            result = "app service called failed, most likely due to wrong parameters sent to it";
                            break;
                        case AppServiceResponseStatus.ResourceLimitsExceeded:
                            result = "app service exceeded the resources allocated to it and had to be terminated";
                            break;
                        case AppServiceResponseStatus.Unknown:
                            result = "unknown error while sending the request";
                            break;
                    }

As we already know by know, we receive a ValueSet as response message. In my sample, I am returning only the response string. That’s it, we are already able to run use the AppService via the Connector. For demo purposes, I added also a simple AppService consumer app. Once the user puts in a question and hits the answer button, the result from the AppService gets displayed. All we need is just one line of code:

            AnswerTextBlock.Text = await SampleAppServiceConnector.Connector.Instance.GetResponse(QuestionTextBox.Text);

Pretty easy to use, right? Here is a screen shot from the consumer app:

image

That’s all we need for our AppService. Bonus of the project structure I used: You can provide a Nuget Package for other devs to consume your AppService. How? I will write about this in my next blog post.

Even if this is not a MVVM structured app, it absolutely works in there, too. If you want to have a look on a live in the Store app that uses MVVM and an AppService, click here. For using the AppService within your app, just download this Nuget Package into your app. Otherwise, I created a complete working sample and pushed it on my Github account right here. Feel free to play around with it to explore AppServices a bit more. As always, I hope this post is helpful for some of you.

Happy coding, everyone!

How to create a RSS feed web tile with notifications for your Microsoft Band

This is a blog post not only for developers, but also for users (I will try to get not to technical in this post).  I managed to buy a Microsoft Band 2 for me here in Europe two weeks ago, and of course I am still exploring all the functionality that it has. A web tile is one of the cool features it supports – with a web tile, you can add your digital footprint to the Microsoft Band. And the best thing: you don’t need to be a developer to create your own! Microsoft provides a web kit that creates the tile for you!

Let’s have a look at the (not so hard to understand) steps it takes to create your own web tile:

The First step is to choose the layout, which also describes the type of the web tile:

Screenshot (82)

After selecting the feed tile template, you need to find the RSS url of your blog or other source site. Paste it in the desired field and hit the next button.

Screenshot (83)

Microsoft’s site now reads your RSS feed and provides you the single fields that come with your feed. When you hover with your mouse over the fields, they’’ll get highlighted. Just drag and drop them into the Microsoft Band preview image on the left hand side.

Screenshot (77)

Now that you have selected the data that should appear on the Microsoft Band, let’s set up the notification for the web tile. This is where it gets a bit tricky, but most feeds should be covered by the following image:

Screenshot (79)

No worries, I am telling you what is done here. The first and second line is the title and the description of the notification. You can put in there whatever you like. The most important part is the condition expression below the Band preview. Sadly the documentation provided by Microsoft is not as detailed for feed tiles as it should. Luckily, I found a post at StackOverflow that explains a little bit more. If you’re a developer, feel free to read the full text. If you are a user: just drag and drop the guid field of the “item” section into the first and also into the last field and set the condition to not equal. If your feed gets a new item, you will get a notification on your band with that. This condition looks if there is any new guid in the items list of your feed – and if so, sends out the notification and shows the badge.

In the last step, we just need to provide some details about the web tile we have created. If you want to have all features, you must provide both images:

Screenshot (80)

If you want to have control on how the image looks like, you should provide the images already flattened into a transparent and white image already. The result could look very creepy otherwise. After that, you have finally created your web tile – congratulations!

Screenshot (81)

Once you have downloaded the web tile, you just need to mail it to yourself or anyone who wants to use it. The other option is to put it on your OneDrive and just share a link to your web tile. To share the link you need to add the link of your online storage to this: “mshealth-webtile://?action=download-manifest&url=”. The web tile I created for my blog is in this case: mshealth-webtile://?action=download-manifest&url=http://1drv.ms/1TDRGSC . This link only works on phones (also Android and iOS). It opens the Microsoft Health app (that needs to be installed for the usage of web tiles, anyways) and asks you to install the web tile:

wp_ss_20160226_0001

Once you have done that, your web tile is ready to go. Once you have a new entry in your RSS feed, the notification should appear on your band. If you want to force the update, just force the Microsoft Health app to sync with your band. After that, you should see the notification and also the badge count. Here is a shot of the one I did for testing:

WP_20160226_17_48_20_Rich_LI

I only began to play around with web tiles, and already was able to create a pretty good result so far. As I will explore them more and more, I will continue to blog about it. In the meantime, I hope this blog post is helpful for some of you. Have fun, everybody!

Review of 2015–my first year in Switzerland

2015 was once again a year where a lot happened. My year began with the start of a new job – I am now employed as a full time developer at the Swiss Shareholder register ShareCommService AG. The first days in Switzerland where full of trouble, as I needed to start from scratch in a new country. I found a room in a shared appartment, which was quite ok for me alone. Internet, phone, insurance, pass port – these were the things I had to do in the first weeks besides learning all the new things that you usually do when entering a new company.

timerarmvvmAs part of my new job, it was also heavily demanded that I finally get deeply into MVVM. I always read a lot about that, but avoided it because I wanted to get things done in my private projects. My MVVM learning project was a WPF timer app that supports resuming, multiple timers and more. I learned it in the only right way: without any frameworks/toolkits, which helps a lot to understand what is going on. Needless to say that I am happy to be past this point, as we are using MVVM Light a lot in our LOB applications. LOB (Line-of-Business) applications are different from what I have done before. They are used only internally and directly affect our daily business. I also learned more about SQL and databases, and also SignalR took a big part of my learning curve.

I have the luck to learn from Roman Müller, who has a gigantic amount of experience in programming and also has always some funny programming story to tell from his past. Together with Reto, the second programmer in our team, he teached me a lot – not only programming things, but also better ways to analyze and think about situations where you can end in programming. I am really thankful to be part of this team. Our system administrator Stefan, which I like to refer as a ‘BOFH with the heart on the right place’, makes the team complete.

During the year, I participated also in several Annual General Meetings (AGM) of our customers. This was very helpful for me to understand my new job, as we are responsible for all things regarding the votings on their agenda.

My first private project this year was to rewrite Voices Admin as a universal (Windows 8.1) app. Of course I did it as plain MVVM app, and it helped me a lot to get even deeper into it, and also boosted my learning curve in my daily job. I updated my UserVoice library as well to be fully portable in the meantime. Currently, I am working on the UWP version of UniShare.

voices admin

My family stayed in Germany for several private reasons in the first month of the year. Beginning in August, we moved completely to Switzerland. I am happy that we passed this point as my family is very important to me and is giving me a lot of power. I have to thank my wife and also both of my kids for their understanding, as being a programmer is often very time consuming.

I also discovered a completely new area: the Internet of Things. With the Rasperry Pi2 supporting the Windows 10 IoT Core, I played around with it, learned a few new things about building hardware – and build a prototype for internal testings.

raspi2proto

You see, I had a year full of action, and I tried to make this post as short as possible. I am looking forward to 2016, where my developer story will continue. I did also blog only a few things this year, and I am trying to keep things up and post more frequently next year.

For now, I whish everyone all the best for the end of this year and also for 2016!

How to implement a simple messenger (for MVVM user controls and apps)

messaging

User controls are awesome. You put together a simple to use (in the best case, that is) component to reuse in your project(s). Sometimes, you even put that control into a (portable) class library to make it available across platforms. Most user controls are written without MVVM, using just DependencyProperties and the matching code behind file.

But – it is possible to create a user control that comes with its own ViewModel, keeping only the DependencyProperties in code behind. There are some limits when it comes to values that are generated by the view of your control. You can’t get them into your ViewModel without creating a reference to it (which may break the MVVM pattern in some eyes). Well, some will argument “who cares, I need to get this working, so I am getting a reference to the DataContext”. This is ok, but there is also another, in my opinion more elegant solution. A class that listens for those changed values, pulling them into your ViewModel – a so called messenger.

Some of you might have used a Framework/Toolkit like MVVMLight, Prism or similar. If you want to use them in a class library, you will find some stones in your way like a missing ViewModelLocator and more. At work, I am working on a universal user control for our LOB applications. Since the control involves a lot of values from its view, I needed a smart and fast way to get those into my ViewModel. I achieved it with my own simple messenger, enabling me to avoid any Framework/Toolkit in my control.

Here is how I did it. First I created a new Singleton class. If you do not know what a Singleton is, just click on the link in the sentence before. Long story short: a Singleton makes the class static, and makes sure that there is only one instance that all other classes are working with (to ultimately get the correct values). [Hint: it may happen that due to some bad timing, you are still having more than one instance. In this case, you should have a look into a different way of implementation the call to the Singleton instance.]

In my case, I am using the simple implementation, which automatically creates the first instance if there is none:

    public class SimpleMessenger
    {
        private static SimpleMessenger _instance;

        public static SimpleMessenger Instance => _instance ?? (_instance = new SimpleMessenger());
     }

The next step is to create an EventHandler, that informs us when the SimpleMessenger has new values. It makes absolutely sense to create your own EventArgs to be passed into the EventHandler. Just collect the data that you want to provide in a class that derives from EventArgs, and make the EventHandler using this class as its event data:

        //declaring EventHandler
        public event EventHandler<MessageValueChangedEventArgs> MessageValueChanged;


        //custom event args class
        public class MessageValueChangedEventArgs : EventArgs
        {

            public string PropertyName { get; set; }

            public object OldValue { get; set; }

            public object NewValue { get; set; }
        }

The most important function in this class is to raise the event:

        //raising the event for a property
        public void RaiseMessageValueChanged(string propertyName, object oldValue, object value)
        {
            MessageValueChanged?.Invoke(this, new MessageValueChangedEventArgs() { PropertyName = propertyName, NewValue = value, OldValue = oldValue });
        }

I am using just three basic values that are needed: the name of the property that changed, its old and its updated value. This already enables me to send data between View and ViewModel, or even to outside of my control. Of course, you want to see how one does send “messages” with my SimpleMessenger. It’s pretty simple, too.

First, you need to get a reference to the current instance:

        private SimpleMessenger _simpleMessenger;

        public MainPage()
        {
            this.InitializeComponent();

            _simpleMessenger = SimpleMessenger.Instance;
         }

To send data, just use the RaiseMessageValueChanged event:

_simpleMessenger.RaiseMessageValueChanged("RootGridSize", e.PreviousSize, e.NewSize);

Last but not least, we are also able to read those values in some other place:

        private SimpleMessenger _simpleMessenger;

        public MainViewModel()
        {
            _simpleMessenger = SimpleMessenger.Instance;
            _simpleMessenger.MessageValueChanged += OnSimpleMessengerValueChanged;
        }
        
        private void OnSimpleMessengerValueChanged(object sender, SimpleMessenger.MessageValueChangedEventArgs e)
        {
            if (e.PropertyName == "RootGridSize")
            {
                var size = (Size)e.NewValue;

                Debug.WriteLine($"Current Size: {size.Height}x{size.Width}");
            }

        }

As you can see, it is simple to use this class to get values in decoupled way (like the MVVM pattern requires). Of course, you still have to take care of not to overuse this. I am using it for example to get the changed values of DependencyProperties that my control has into the ViewModel (which would otherwise only be possible with a reference to it.).

This SimpleMessenger may not be as powerful as those in the popular Frameworks/Toolkits, but for usage in user controls or small apps it should fit in perfect.  I attached a very simple project to demonstrate the SimpleMessenger. Just start the project, and use your mouse to resize the app window. It will write the Size of the root grid to the console.

Download sample

As always, I hope this post is helpful for some of you.

Happy coding!

How to implement a simple notification system in MVVM Windows 8.1 Universal apps

screenshot_07042015_152814

If your app performs actions, you most probably want to add also some confirmation if an action has finished. There are some ways to do this, like using local toast notifications or MessageDialogs. While I was working on Voices Admin v2, which is a universal app, I came along with a helper to simplify using local toast notifications. However, there came the point, where I got annoyed by the sound of these, and I looked into possible ways to replace them. My solution is a simple notification system, that uses the MVVM Light Messenger.

The first thing I did was adding a new property that broadcasts its PropertyChangedMessage to my ExtendedViewModelBase (which inherits from the MVVM Light ViewModelBase). This simplifies setting the notification text across multiple ViewModels as I don’t need to create a property in every ViewModel of my app:

public class ExtendedViewModelBase : ViewModelBase
    {
        public ExtendedViewModelBase()
        {
            
        }


        /// <summary>
        /// The <see cref="NotificationText" /> property's name.
        /// </summary>
        public const string NotificationTextPropertyName = "NotificationText";

        private string _notificationText = string.Empty;

        /// <summary>
        /// Sets and gets the NotificationText property.
        /// Changes to that property's value raise the PropertyChanged event. 
        /// This property's value is broadcasted by the MessengerInstance when it changes.
        /// </summary>
        public string NotificationText
        {
            get
            {
                return  _notificationText = string.Empty;
            }
            set
            {
                Set(() => NotificationText, ref _notificationText, value, true);
            }
        }
   }

The second step is to create the possibility to bind this into my view. I am using a custom PageBase class to simplify this. For those binding purposes it is common to add a DependencyProperty, and this is exactly what I did:

/// <summary>
        /// global property to bind the notification text against
        /// </summary>
        public static readonly DependencyProperty AppNotificationTextProperty = DependencyProperty.Register(
            "AppNotificationText", typeof (string), typeof (PageBase), new PropertyMetadata(string.Empty, (s, e) =>
            {
                var current = s as PageBase;

                if (current == null)
                {
                    return;
                }

                current.CheckifNotificationMessageIsNeeded(s);
            }));

        /// <summary>
        /// gets or sets the AppNotificationText
        /// </summary>
        public string AppNotificationText
        {
            get { return (string)GetValue(AppNotificationTextProperty); }
            set { SetValue(AppNotificationTextProperty, value); }}

You may have noticed that I hooked up into the PropertyChangedCallback of the DependecyProperty, which passes the execution to an separate method. Before we’ll have a look on that method, we need to add two private members to my PageBase: one for a StackPanel (mainly to set the Background color) and another one for Textblock. This is needed because this is the visible part of the notification. In the constructor of my PageBase class, I am filling them with live and connect them together:

            //instantiate and create StackPanel and TextBlock
            //you can put anything you want in the panel
            _panel = new StackPanel()
            {
                Background = new SolidColorBrush(Colors.Blue),
                Visibility = Visibility.Collapsed,
            };

            _textBlock = new TextBlock()
            {
                FontSize = 20,
                Margin = new Thickness(39, 10, 10, 10),
                TextAlignment = TextAlignment.Center
            };
            _panel.Children.Add(_textBlock);

The next thing we need to do is the FindChildren<T> helper method, which I took from the MSDN docs:

        /// <summary>
        /// Gets a list of DependencyObjects from the Visual Tree
        /// </summary>
        /// <typeparam name="T">the type of the desired object</typeparam>
        /// <param name="results">List of children</param>
        /// <param name="startNode">the DependencyObject to start the search with</param>
        public static void FindChildren<T>(List<T> results, DependencyObject startNode) where T : DependencyObject
        {
            int count = VisualTreeHelper.GetChildrenCount(startNode);
            for (int i = 0; i < count; i++)
            {
                var current = VisualTreeHelper.GetChild(startNode, i);
                if ((current.GetType()) == typeof(T) || (current.GetType().GetTypeInfo().IsSubclassOf(typeof(T))))
                {
                    T asType = (T)current;
                    results.Add(asType);
                }
                FindChildren<T>(results, current);
            }
         }

This helper enables us to find the top level grid, where we will add the StackPanel and control its visibilty and the TextBlock’s text. Which we are doing with the CheckifNotificationMessageIsNeeded() method:

        /// <summary>
        /// handles the visibility of the notification
        /// </summary>
        /// <param name="currentDependencyObject">the primary depenedency object to start with</param>
        private void CheckifNotificationMessageIsNeeded(DependencyObject currentDependencyObject)
        {
            if (currentDependencyObject == null) return;

            var children = new List<DependencyObject>();
            FindChildren(children, currentDependencyObject);
            if (children.Count == 0) return;

            var rootGrid = (Grid)children.FirstOrDefault(i => i.GetType() == typeof(Grid));

            if (rootGrid != null)

                if (!string.IsNullOrEmpty(AppNotificationText))
                {
                    if (!rootGrid.Children.Contains(_panel))
                    {
                        rootGrid.RowDefinitions.Add(new RowDefinition() {Height = new GridLength(_panel.ActualHeight, GridUnitType.Auto)});
                        _panel.SetValue(Grid.RowProperty, rootGrid.RowDefinitions.Count);

                        rootGrid.Children.Add(_panel);
                    }

                    _textBlock.Text = AppNotificationText;
                    _panel.Visibility = Visibility.Visible;
                }
                else if (string.IsNullOrEmpty(AppNotificationText))
                {
                    _textBlock.Text = string.Empty;
                    _panel.Visibility = Visibility.Collapsed;
                }
        }

Once we have the rootGrid on our Page, we are adding a new Row, set the StackPanel’s Grid.Row property to that and finally add the StackPanel to the Grid’s Children – but only if it does not exist already. No everytime the AppNotificationText property changes, the visibility of the StackPanel changes accordingly. Same counts for the TextBlock’s text. That’s all we need to do in the PageBase class.

The final bits of code we have to add are in the MainViewModel. I am using the MainViewModel as a kind of root ViewModel, which controls values and actions that are needed across multiple ViewModels. If you do not use it in the same way, you might need to write that code in all of your ViewModels where you want to use the notifications. The biggest advantage of my way is that the notification system (and other things) also works across pages.

The first thing we need is of course a property for the notification Text, which we will use to bind against on all pages where we want to use the notification system:

        /// <summary>
        /// The <see cref="GlobalNotificationText" /> property's name.
        /// </summary>
        public const string GlobalNotificationTextPropertyName = "GlobalNotificationText";

        private string _globalNotificationText = string.Empty;

        /// <summary>
        /// Sets and gets the GlobalNotificationText property.
        /// Changes to that property's value raise the PropertyChanged event. 
        /// </summary>
        public string GlobalNotificationText
        {
            get
            {
                return _globalNotificationText;
            }
            set
            {
                Set(() => GlobalNotificationText, ref _globalNotificationText, value);
            }
        }

Now we have this, we are hooking into the MVVM Messenger to catch the broadcasted NotificationText’s PropertyChangedMessage:

            Messenger.Default.Register<PropertyChangedMessage<string>>(this, message =>
            {
                if (message.PropertyName == ExtendedViewModelBase.NotificationTextPropertyName)
                {
                }
             });

If we would stop here, you would need to find a good point to set the NotificationText (and/or the GlobalNotificationText) property back to an empty string. This can be like the search a needle in the hay, believe me. That’s why I am giving every notification 5 seconds to be displayed, and the I am resetting the GlobalNotificationText  property in my MainViewModel automatically. To achieve this goal, I am using a simple DispatcherTimer with an Interval of 1 second:

            _notificationTimer = new DispatcherTimer() { Interval = new TimeSpan(0, 0, 1) };

DispatcherTimer has a Tick event, which fires every time a Tick happened. In our case, it fires every second. Hooking up into this event is essential, so add this line of code and let Visual Studio create the handler for you:

//in constructor:       
_notificationTimer.Tick += _notificationTimer_Tick;

//generated handler:
        private void _notificationTimer_Tick(object sender, object e)
        {
        }

Inside the Tick event handler, I am counting the ticks (using a private member in my MainViewModel). Once the timer passed 5 seconds, I am stopping the DispatcherTimer, reset the counter and finally set the GlobalNotificationText  property back to empty, which causes the notification to disappear:

            _notificationTimerElapsedSeconds++;

            if (_notificationTimerElapsedSeconds > 5)
            {
                _notificationTimer.Stop();
                _notificationTimerElapsedSeconds = 0;
                GlobalNotificationText = string.Empty;
            }

Of course we also need to start the DispatcherTimer. The perfect time for this is within the handler of the received PropertyChangedMessage we added earlier:

            //register for the global NotificationText PropertyChangedMessage from all VMs that derive from ExtendenViewModelBase
            Messenger.Default.Register<PropertyChangedMessage<string>>(this, message =>
            {
                if (message.PropertyName == ExtendedViewModelBase.NotificationTextPropertyName)
                {
                    if (!_notificationTimer.IsEnabled)
                    {
                        _notificationTimer.Start();
                    }
                    else
                    {
                        _notificationTimerElapsedSeconds = 0;
                    }

                    GlobalNotificationText = message.NewValue;
                }
            });

I am just checking if the DispatcherTimer is not yet enabled (= running) and start the timer in this case. If it is already running, I am just resetting my counter property to make sure that the notification is visible for 5 seconds again.

That’s it. Your MVVM (Light) app has now a simple and not so annoying notification system. It also provides the same experience across both platforms. There are sure ways to improve this here and there, that’s why I put up a sample to play around and contribute to on my Github account.

As always, I hope this post is helpful for some of you.

Happy coding!

How to add Microsoft Application Insights v1 to your Windows 8.1 Universal app

Late in 2014, Microsoft finally started Application Insights (AI), their own telemetry service for all kind of apps. For Windows (Phone) 8.1 apps, the service was a long running beta. This month, Microsoft finally released version 1.0 of Application Insights for Windows apps.

Screenshot (15)

However, if you are upgrading from a previous version, you will see that AI will no longer send any data to Azure. This has a very simple reason. Microsoft moved the configuration from the former ApplicationInsights.config file to a class called WindowsAppInitializer. I only found this out because I commented at the corresponding documentation site, which causes Microsoft to send me an email with a link to the solution in the forums. You will not find these info in the documentation as of writing this blog post. Microsoft also updated the docs tonight.

I strongly recommend you to remove all old references in favor of just updating to avoid any glitches with the new API.

I played around with the new WindowsAppInitializer class. If you want to collect all data with the automatic WindowsCollectors, all you have to add to your code is one line in your App.xaml.cs constructor (Microsoft recommends to add it before all other code):

WindowsAppInitializer.InitializeAsync("your instrumentation key”);

That’s it. Really. Here’s a screen shot of the test app in Visual Studio I created to play around with the new WindowsAppInitializer class:

Screenshot (24)

As you can see, telemetry data gets written to the debug output, and with that, it will be submitted to your Azure account. If you do not want to use all Collectors, just add those you want to use after your InstrumentationKey, separated with ‘|’ in the IninitalizeAsync Method.

Adding custom telemetry data collection is still possible. Quick sample:

var tc = new TelemetryClient();
tc.TrackEvent("MainPage loaded... [WP TestEvent]");

This will send this string as a custom event to your Azure account. For more info about custom telemetry data, check this page.

As always, I hope this blog post is helpful for some of you.

Happy coding!

[Updated] String Encryption in Windows 8.1 Universal apps

image credit: Maksim Kabakou, Fotolia.com
image credit: Maksim Kabakou, Fotolia.com

[Updated: This post caused a lot of controversy and bad voices, but luckily also some constructive feedback. This is not the initial, but the updated version of this post.]

One of the goals of a Universal Windows app project is to simplify the life of our users. Microsoft provides access to RoamingSettings as well as the RoamingFolder to achieve this goal.

The usage of this storage is fairly simple (it is the same as using the local counterparts). However, one big point is how to save those settings and files securely. Nowadays, a lot of users are even more concerned about security than before, and it makes all sense to encrypt synchronized data.

This is how I came a long with a helper class string encryption. I have searched a lot throughout the Web, but apparently this is not a topic to be discussed openly but behind closed doors. I partly understand that, but I want to say thanks to Ginny Caughey at this point for her feedback on security, and also thank Joost van Schaik for his feedback that “forced” me to change my helper class to extension methods, which makes the usage more readable. If you want to learn more about Extension Methods, this link helped me to understand them and made me changing my code in about 5 minutes.

Let’s talk about security. There are two patterns for encrypting sensitive data: using symmetric algorithm and using asymmetric algorithm. The symmetric key encryption is secure, as long as you have a truly unique identifier that you can use as encryption key. Being very fast, using the symmetric algorithm is only as secure as the key that is used for encryption (obviously, I did it wrong in the first place, that’s why the code is updated). More security is achieved with the asymmetric algorithm, where a public and a private key are used for encryption. The downside of this higher level of security is that it takes longer to perform those actions. There are also more differences between those methods, but that would fill a whole book.

I have learned that on Android and iOS, often the AdvertisingId is used for such operations. Also Windows 8.1 (both phone and PC/tablet) have such an Id, provided by the AdvertisingManager class. Be aware that the id is per-user and per-device and users can switch this off or even reset their advertising id, so this is not a good idea to use. In Windows 8.1 Runtime projects (both phone and tablet/PC, we luckily have the PasswordVault class. This brings us some key advantages: the PasswordVault is encrypted and it does roam to trusted devices. This is what I am using for saving the keys, being it the symmetric one or the asymmetric ones.

Before we will have a look at my Extension methods, I have to put in a disclaimer. I am not saying that my way is the nonplus ultra way to encrypt strings. I do also not say that my way provides 100% security (which in fact does not even exist). My way provides security at a good level, but that level surely can be improved. I will take no responsibility for the security of apps that are using this.  

Let’s have a look at my Extension methods that will help you securing your data.

Symmetric Key Encryption

My symmetric encryption methods were using a pre shared key. I received a lot of feedback that this does not make any sense as it throws away the security factor, especially as the Guid can be recalculated. So I changed the method to use random data, that is generated from the CryptographiBuffer.GenerateRandom() method. Then I am putting this into an Base64 encoded string to pass it over to the PasswordVault:

        public static string GetKeyMaterialString(string resource = null, string username = null)
        {
            string key = "";

            if (string.IsNullOrEmpty(resource) && string.IsNullOrEmpty(username))
            {
                //replace with your resource name if suitable
                resource = "symmetricKey";
                //replace with your user's name/identifier
                username = "sampleUserName";                                
            }            

            //using try catch as FindAllByResource will throw an exception anyways if the specified resource is not found
            try
            {
                //search for our saved symmetric key
                var findSymmetricKey = _passwordVault.FindAllByResource(resource);
                //calling RetrievePassword you MUST!
                findSymmetricKey[0].RetrievePassword();
                key = findSymmetricKey[0].Password;
            }
            catch (Exception)
            {
                //getting a true random key buffer with a length of 32 bytes
                IBuffer randomKeyBuffer = CryptographicBuffer.GenerateRandom(32);

                key = CryptographicBuffer.EncodeToBase64String(randomKeyBuffer); 

                _passwordVault.Add(new PasswordCredential(resource, username, key));
            }
            
            return key;
        }

The resource string as well as the username is needed to save the key into the PasswordVault. The FindAllByResource() method will throw an Exception if no credentials are found, in this case we are generating them from scratch in the catch block.

The encryption method is pretty straight forward as well. Microsoft does all the complicated calculating stuff, we just need to call the proper methods. What you get is a Base64 encoded string that easily can be saved into the ApplicationSettings or wherever you need it. Here is the complete extension method:

        public static string EncryptStringSymmetric(this string text)
        {
            string encryptedString = "";

            try
            {
                //load the alghorithm providers
                var symmetricKeyProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);

                //create the symmetric key that is used to encrypt the string from random keystring
                var cryptoKey = symmetricKeyProvider.CreateSymmetricKey(CryptographicBuffer.DecodeFromBase64String(GetKeyMaterialString()));

                //create the IBuffer that is for the string
                IBuffer buffer = CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes(text));

                //encrypt the byte array with the symmetric key
                encryptedString = CryptographicBuffer.EncodeToBase64String(CryptographicEngine.Encrypt(cryptoKey, buffer, null));

                //return the Base64 string representation of the encrypted string byte array
                return encryptedString;
            }
            catch (Exception)
            {
                return null;
            }

        }

 


The decryption method of course reverses all this. First, it loads the saved key from the password fault, and then decrypts and returns then the plain text string:

        public static string DecryptStringSymmetric(this string text)
        {
            string decryptedString = "";

            try
            {
                //load the alghorithm providers
                var symmetricKeyProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);

                //create the symmetric key that is used to encrypt the string from random keystring
                var cryptoKey = symmetricKeyProvider.CreateSymmetricKey(CryptographicBuffer.DecodeFromBase64String(GetKeyMaterialString()));

                //decode the input Base64 string
                IBuffer buffer = CryptographicBuffer.DecodeFromBase64String(text);
                //declare new byte array
                byte[] dectryptedBytes;
                //decrypt the IBuffer back to byte array
                CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(cryptoKey, buffer, null), out dectryptedBytes);
                //get string back from the byte array
                decryptedString = Encoding.UTF8.GetString(dectryptedBytes, 0, dectryptedBytes.Length);

                //return plain text
                return decryptedString;
            }
            catch (Exception)
            {
                return null;
            }
        }

 

Both methods return null if anything did not work like excepted. This should help you to easily check if something went wrong in there. Here is how to use those methods:

Encrypting the string:

var encryptedString = stringToEncrypt.EncryptStringSymmetric();

Decrypting the string:

var dectryptedString = stringToDecrypt.DecryptStringSymmetric();

Asymmetric Key Encryption

Like I already wrote, for asymmetric encryption always two keys are used. The method to get the keys is there slightly different:

        public static Dictionary<string, string> GetAsymmetricKeyPair(string username = null)
        {
            Dictionary<string, string> keyDictionary;
            const string privKey = "asymmetricPrivateKey";
            const string pubKey = "asymmetricPublicKey";

            if (string.IsNullOrEmpty(username))
            {
                //replace with your user's name/identifier 
                username = "sampleUserName";
            }

            //using try catch as FindAllByResource will throw an exception anyways if the specified resource is not found
            try
            {
                //search for our save asymmetric keys
                var findAsymmetricPrivateKey = _passwordVault.FindAllByResource(privKey);
                //calling RetrievePassword you MUST!
                findAsymmetricPrivateKey[0].RetrievePassword();
                var findAsymmetricPublicKey = _passwordVault.FindAllByResource(pubKey);
                //calling RetrievePassword you MUST!
                findAsymmetricPublicKey[0].RetrievePassword();

                //loading our keys into a new Dictionary
                keyDictionary = new Dictionary<string, string>()
                {
                    {privKey, findAsymmetricPrivateKey[0].Password},
                    {pubKey, findAsymmetricPublicKey[0].Password}
                };
            }
            catch (Exception)
            {
                //declaring the Key Algortihm Provider and creating the KeyPair
                var asymmetricKeyProvider =
                    AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
                CryptographicKey cryptographicKeyPair = asymmetricKeyProvider.CreateKeyPair(512);

                //converting the KeyPair into IBuffers
                IBuffer privateKeyBuffer =
                    cryptographicKeyPair.Export(CryptographicPrivateKeyBlobType.Pkcs1RsaPrivateKey);
                IBuffer publicKeyBuffer =
                    cryptographicKeyPair.ExportPublicKey(CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey);

                //encoding the key IBuffers into Base64 Strings and adding them to a new Dictionary
                keyDictionary = new Dictionary<string, string>
                {
                    {privKey, CryptographicBuffer.EncodeToBase64String(privateKeyBuffer)},
                    {pubKey, CryptographicBuffer.EncodeToBase64String(publicKeyBuffer)}
                };

                //saving the newly generated keys in PasswordVault
                //it is recommended to save the both keys separated from each other, though
                _passwordVault.Add(new PasswordCredential(privKey, username, keyDictionary[privKey]));
                //_passwordVault.Add(new PasswordCredential(pubKey, username, keyDictionary[pubKey]));
            }

            //return new Dictionary
            return keyDictionary;
        }

As you can see, I am creating a Dictionary that holds the two keys so we can work with. I also use another key generating method, specially made for asymmetric encryption. I store those two keys separated from each other into the PasswordVault in the end.

The encryption follows basically the same structure as the symmetric key encryption method. Due to the fact I already have two different keys, I think this is ok for the scenario of passing values between the Windows Phone and Windows  project. Eventually I will change that in future when I see the need for it. Notice that for encryption, always the public key is used. The public key should also be saved separated from the private key. So here is the complete method:

        public static string EncryptStringAsymmetric(this string text, string publicKey = null)
        {
            //making sure we are providing a public key
            if (string.IsNullOrEmpty(publicKey))
            {
                var keyPairs = GetAsymmetricKeyPair();
                publicKey = keyPairs["asymmetricPublicKey"];
            }

            try
            {
                //converting the public key into an IBuffer
                IBuffer keyBuffer = CryptographicBuffer.DecodeFromBase64String(publicKey);
                
                //load the public key and the algorithm provider
                var asymmetricAlgorithmProvider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
                var cryptoKey = asymmetricAlgorithmProvider.ImportPublicKey(keyBuffer, CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey);

                //converting the string into an IBuffer
                IBuffer buffer = CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes(text));

                string encryptedString = "";

                //perform the encryption
                encryptedString = CryptographicBuffer.EncodeToBase64String(CryptographicEngine.Encrypt(cryptoKey, buffer, null));

                //return the Base64 string representation of the encrypted string
                return encryptedString;
            }
            catch (Exception)
            {
                return null;
            }

        }

The decryption of the encrypted string works also in a similar way to the symmetric one, except we are using the private key of our asymmetric key pair. To be able to do this, we need to use the ImportKeyPair method, whose name is a bit misleading in my opinion. In fact, we even need to specify that we want to import the private key and not the whole key pair. But even with that, decryption works like expected:

        public static string DecryptStringAsymmetric(this string text, string privateKey = null)
        {
            //making sure we are providing a public key
            if (string.IsNullOrEmpty(privateKey))
            {
                    var keyPairs = GetAsymmetricKeyPair();
                privateKey = keyPairs["asymmetricPrivateKey"];
            }

            try
            {
                //converting the private key into an IBuffer
                IBuffer keyBuffer = CryptographicBuffer.DecodeFromBase64String(privateKey);

                //load the private key and the algorithm provider
                var asymmetricAlgorithmProvider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
                var cryptoKey = asymmetricAlgorithmProvider.ImportKeyPair(keyBuffer, CryptographicPrivateKeyBlobType.Pkcs1RsaPrivateKey);

                //converting the encrypted text into an IBuffer
                IBuffer buffer = CryptographicBuffer.DecodeFromBase64String(text);

                //cdecrypting the IBuffer and convert its content into a Byte array 
                byte[] decryptedBytes;
                CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(cryptoKey, buffer, null), out decryptedBytes);

                string decryptedString = "";

                //getting back the plain text 
                decryptedString = Encoding.UTF8.GetString(decryptedBytes, 0, decryptedBytes.Length);

                return decryptedString;
            }
            catch (Exception)
            {
                return null;
            }
        }

Like the symmetric methods, also the asymmetric methods return null if something went wrong. Here is how to use them:

Encrypting the string:

var encryptedString = stringToEncyrpt.EncryptStringAsymmetric();

Decrypting the string:

var decryptedString = stringToDecrypt.DecryptStringAsymmetric();

As you can see, securing strings does not have to be more complicated than this. Using the PasswordVault, we have a truly secure place to store the keys (that need to be saved privately and secure), the rest is done by the methods provided by the operating system. I am by far not a security researcher or expert, but this class should provide a good level of security for string encryption in Windows 8.1 universal apps.

If you know more about security or have ideas to improve this helper class, I put up a sample project on Github where you also can play around with the class and the simple app I created for it. Feel free to contribute to this class or discuss in the comments below.

Happy coding, everyone!