Corrado's Blog 2.0

Online thoughts of a technology funatic

UWP Localization inside a library

Many of my blog posts comes from personal real world needs, since many of them requires more than just an internet search, when i struggle with some of them I try to share my experience with the online community.
The goal of this post is very simple at first sight: Localize a control that resides inside a control library and make the language used by the control different from the OS one (e.g. Control text in German while running on an English version of Windows)
The master of UWP localization documentation is this MSDN link, so I won’t add anything else since it will just result in a duplicate,
Following the MSDN documentation I’ve created two projects: A UWP client (LocalizationInLib) and a control library project (ControlLibrary) inside the latter I’ve created a Strings folder containing the default localization file Resources.resw and inside of it an additional “it” folder containing the italian translation of master Resources.resw content.

Here’s the project structure


and here’s what’s inside both Resources.resw files



Nothing new until now if you read the previously mentioned MSDN link.

Let’s now define our simple MyTimer control in XAML and a SetLanguage method that accept the control culture to use.

This way we can invoke SetLanguage from the client application depending of what culture the user selected in main app.
We have now reached the core point of this post and what made me hit the head several times: what code should I use to load the proper resources at runtime? after many tests and investigations here’s what I ended up with:

Important detail is to use the proper namespace inside GetForViewIndependentUse otherwise the method will fail.
Just few lines of code, but took me some time to figure out how to properly combine them, so I hope this will help you in future.

Detect Application closing in UWP

Nearly every application when user closes it using the “X” button on upper right corner prompts something like this


Asking user if he wants to save actual work or cancel closing operation. 
Doing this in a UWP application is far from trivial, sounds strange uh? Smile

Despite some options are available (like CoreWindow esposes a Closed event but it never fires) the only available solution sounded to be this one which is unfortunately complex and unreliable. 
From Creators update (version 1703) a new class SystemNavigationManagerPreview  has been added and this class exposes a CloseRequested event (yeah!)
Ok, let’s see how it works, let’s fire up a brand new UWP app inside Visual Studio and let’s add this code inside MainPage.Xaml codebehind.

Let’s put a breakpoint inside OnCloseRequested method, run the app and try closing the window clicking the upper right “X” button.
The breakpoint doesn’t it right? so What’s wrong with that? nothing indeed, we just miss an important detail:  In order to work, you need to add a restricted capability inside package.appmanifest, the one we need is AppClose Confirmation that MSDN describes as: confirmAppClose restricted capability allows apps to close themselves, their own windows, and delay the closing of their app.

Ok, let’s manually edit the manifest file adding following lines:

Inside Package tag: xmlns:rescap=""

then add rescap to IgnorableNamespacesAttribute: IgnorableNamespaces="uap mp rescap"
Then inside Capabilities tag:
    <Capability Name="internetClient" />
    <rescap:Capability Name="confirmAppClose"/>

Very important: confirmAppClose capability must be listed before any optional DeviceCapability otherwise it won’t work.
Let’s  now try again and… yes! it works! Smile
You can now do whatever you want inside the OnCloseRequest handler, like showing a dialog and if user denies closing setting SystemNavigationCloseRequestedPreviewEventArgs.Handled=true to prevent app from closing.

Please take care of the note inside capabilities declaration page on MSDN:

Some of these restricted capabilities are almost never approved for apps submitted to the Store, except in very specific and limited circumstances. These capabilities are called out in the table below. We recommend not declaring these capabilities in your app if you plan to distribute it through the Store.

I see no reason why Microsoft should prevent this but take note and don’t forget to mention its use inside portal Submission options page

UWP Share target and COM Exception 0×80004002

Goal was very simple initially: Implement a share target inside a UWP application that, when activated, just adds a new entry inside a pre-populated ObservableCollection.
Sound easy right? It doesn’t, and I spent the entire morning fighting against this exception


Let’s see how I solved it.
Download Share Source and Target solution from here I won’t go into code detail because if you need to learn how implement both share source and target you can find a detailed description from Microsoft documentation here:

-Share Source
-Share Target

Let’s dig into critical part of the code:

What shared target does is to load an item into an observable collection:

and this is the code that gets invoked when share operation is invoked

In line 9 we add a new item into shared observable collection and the code fails with an InvalidCastException.
I’m used that when those crazy exception raise most of the times they come from threading issues, in fact share operation is invoked on a secondary thread so my next take has been to marshal the operation this way:

but in this case the dispatched action it doesn’t even get invoked, probably because the main message pump is blocked, nice…

So I tried another way, using Windows.Current’s dispatcher

and in this case action is invoked, but… same error Sad smile probably because the dispatcher is the same as the one used to create the main application window.
I was totally lost now since, while I’ve found many other developers struggling with this, no one posted a working solution (and this lead to the reason of this post) but, don’t know how, I remembered that there’s another way to access a dispatcher and is via CoreApplication class

And… YES, It works! Smile
I honestly don’t know what happens behind the scenes, but frankly, didn’t expected this apparently easy task to turn into a semi nightmare, but glad, with some luck honestly, I won over it.

Trace application flow easily

UWP applications are compiled using .NET Native compiler as detailed here.
This process gives many advantages over JIT compilation:

  • -Up to 60% performance improvement on cold startup times
  • -Up to 40% performance improvement on warm startup times
  • -Less memory consumption of your app when compiled natively
  • -No dependencies on the desktop .NET Runtime installed on the system
  • -Since your app is compiled natively, you get the performance benefits associated with native code (think C++ performance)
  • -You can still take advantage of the industry-leading C# or VB programming languages, and the tools associated with them
  • -You can continue to use the comprehensive and consistent programming model available with .NET– with extensive APIs to write business logic, built-in memory management, and exception handling.

This brings a side effect:  Since app is compiled natively and logged StackTrace information is lost resulting in a series of meaningless series of entries like:

SharedLibrary!<BaseAddress>+0x38449f at
SharedLibrary!<BaseAddress>+0x3842cd Exception_EndOfInnerExceptionStack at
SharedLibrary!<BaseAddress>+0×384405 at
SharedLibrary!<BaseAddress>+0x3bd80d at
SharedLibrary!<BaseAddress>+0x3c1f45 at

that tells you nothing about what happened until reported exception, so the only real solution is to keep track of your workflow using custom made logging like:

but this is absolutely tedious and repetitive, so we can simplify it using a good old C# trip based on coupling using keyword and IDisposable.

Let’s create a TraceSession class this way

With this class we can log any part of our code this way:

Much more easier and readable since all you have to do is essentially to write your code inside using block,  if you paired this with a Visual Studio code snippet that generates initial code skeleton implementation becomes nearly invisible.

Consume Google API from UWP

I’m writing this post so that you don’t have to spend too much time as I did to figure how to authenticate and invoke Google APIs from a UWP application.
I found several solutions, mostly outdated, and tons of quite articulated documentation, including the official one from Google, all discussing about the same few APIs, but i got no chance to have it working, until I got to this solution.

So, Lets’s go!

As initial step we need to register our app into Google developer portal, registration will return us a couple of fundamentals info: Client Key and Client Secret.
Navigate to , login and select Credentials under APIs and Services on the left side of the portal.


click on Create credentials and select the oAuthClientID, you will be promped with a similar screen


Required information are, Application Type, Name and Redirect (you can use whatever Uri you want here), when done click Create, this will generate the mandatory Client ID and Client secret info.


Download the code from the sample shows you how to reried logged user informations like name, email, picture…

If you analyze the code you’ll note that we use Xamarin Auth library for all oAuth2 stuff…


and basically the procedure is divided onto three main steps:

1) Get the Google auth token

2) Get oAuth2 token

3) Call Google API passing the oAuth2 token, in our case we retrieve user info, but you can use any API you prefer

There’s not too much to add but the fact that I’ve lost many hours trying to figure out how to make this basic sample working and I agree that using a library, maybe the official one from Google, would be better, but despite several attempts I was not able to make it working on UWP since looks like that some core parts related to authorization are not there yet.

Hope this saved you some headaches Smile

Lottie animations in UWP

Lottie is a library created by Airbnb team that parses animation created using Adobe’s After Effects and exported as json file using Bodymovin plugin.
The library was targeting iOS ,Android and React native initially, but thanks to the hard work of community developers a version for Xamarin and UWP is now also available.

If you don’t have any ready-made animation you can get some (and contribute as well) from LottieFiles large repository.

Note: LottieUWP supports Windows Build 10586+ (November Update) and above

Showing a ‘Lottie’ animation in a UWP application is fairly easy.

-Create a blank UWP application

-Include LottieUWP nuget package (don’t forget to check Include prerelease flag to see it) 


-Include one or more .json file (your own or one downloaded from LottieFiles) representing the animations you want to play and, important, change Build Action to Content


-Add a LottieAnimationView control where you want the animation to appear, as example inside MainPage.Xaml

If you run the app you will see your animation playing endlessly Smile


You can load an animation programmatically using different options, the most common one is probably via the SetAnimationAsync method that also allows you to provide a caching strategy optimization parameter that allows parsed and loaded animation to be cached for reuse.

Adding these lines into MainPage.xaml.cs constructor generates this output


If you want to have even more control, you can subscribe AnimatorUpdated event and inside event handler control the entire animation, in this example I make the animation play faster in the seconf half.


Cool isn’t it? Winking smile

There’s not to much interesting to say about it, if you want more details you can check these links:

-LottieUWP github repository

-#ifDef LottieUWP video on channel 9

Go animating!

Get unique Device Id and Application Id in UWP applications

Sometime you need to get a unique application identifier for your app together with a unique device id for internal processing.

Here’s the code you need:

A note regarding device identifier

As you might see from the involved API name SystemIdentification.GetSystemIdForPublisher() the returned value is unique for the same app publisher, if publisher changes the value changes as well.

Here are the Device Id characteristics

  • -Unique for each system
  • -On any particular system, all apps by the same publisher will get the same value for this ID (for all users). Conversely, apps by different publishers on the same system will obtain different IDs.
  • -Can be created offline
  • -Persists across restarts, reinstalls and upgrades of Windows, including clean installs (please see below for exceptions)
  • -Persists across most hardware modifications
  • -Available in OneCore

Playing with ParallaxView

Those of you who have some Windows Phone development experience will remember the Panorama control for sure.
Control had a nice effect where background content was moving slowly below foreground, this effects is named Parallax and you’ll be glad to know that, starting from Fall Creators Update you can have this effects easily back into your own UWP applications, thanks to ParallaxView parte of the new Fluid Design System.

Let’s see it in action:

Create a new UWP application targeting Fall Creators Update (unfortunately ParallaxView is not available on older platforms)


let’s now add the ParallaxView to MainPage.Xaml

ParallaxView has a Child property that is used to represent the content that is scrolled slowly, in this case I defined it directly inside the ParallaxView.
The key property is Source that you can bind to an element that can be a ScrollViewer or an element that contains a ScrollViewer like a ListView or a RichTextBox. (Note: I tried to nest ListView definition directly inside ParallaxView but seems not to work)
Nothing special to mention about ListBox apart tha:

  1. -I used the ‘new’ PersonPicture control
  2. -The ListView must be placed after the ParallaxView definition, otherwise it wont work

Codebehind is quite straighforward:

The control supports both Verticaland and Horizontal scrolling and the most important property is probably Vertical/HorizontalShift that govers ‘how fast’ background scrolls, chose the one the best fits for you.
Using Vertical/HorizontalStartOffset it is possible to fine tune background scrolling behavior (play with them…)

Here’s final result, what do you think? Smile


Save Win2D CanvasControl content

Win2D is an easy-to-use Windows Runtime API for immediate mode 2D graphics rendering with GPU acceleration that is very helpful in some situations like real time or layered rendering.
This post is about how to save dynamically rendered content to a file for further external processing.

To give you an idea, let’s build a quick Win2D sample.

Create a blank new UWP project and add a NuGet reference to Win2D package


on MainPage.Xaml add following XAML

and this code on relative codebehind

if you now run the sample and change the value of the slider you will see the rectangle moving this way


From the code is evident that each time the value of the slider changes we invalidate the CanvasControl so that OnDraw method gets called and content is redrawn with the new rectangle position.

To save CanvasControl content we basically need to draw actual content into an offscreen render target and use the SaveAsync method to get the stream content.
Here’s the code:

code just draws the same content into a CanvasRenderTarget representing the offscreen renderer and then gets that stream, the remaining code just saves it into a StorageFile.
Off course what’s drawn into offscreen renderer is up to you (as example you might add a watermark) and output format can be changed via CanvasFormatBitmap parameter.


UWP: Read German text from a file

I had some hard times figuring out how to properly read a file that contains typical German characters (e.g umlauts) so I want to share my solution in case are in the same situation.

The magic trick is to register a new provider named “windows-1254” using Encoding.RegisterProvider

Older Posts »