Corrado's Blog 2.0

Online thoughts of a technology funatic

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

Beware of generated XAML in UWP

I admit, this is s strange blog post title but that’s what this post is going to talk about.

I’m working on a UWP app that has different min and target runtimes:


After doing some UI work with Visual Studio & Blend I’ve discovered that the app was crashing on machines without Anniversary edition installed. At the end of a debuggin session I’ve found the reason: The XAML template generated by the tools contains incompatible elements (resources mainly, but also new properties) that are not present on previous builds.

To give you an example, this is an extract from a ComboBox default template, generated by Blend when you use the Template->Edit copy feature:


<Setter Property="Foreground"

Value="{ThemeResource SystemControlForegroundBaseHighBrush}" />

14393 (Anniversary)

<Setter Property="Foreground"

Value="{ThemeResource ComboBoxForeground}" />

The reason of this is because the tools generate the template from the Target version SDK and not the Min version SDK that might even not be present.

The team said that they’re going to give you some warnings in the future when situations like this happen, but in the meantime, at least when you’re doing design work, be sure to selected, the min target version SDK otherwise you might end up in troubles.

Dynamic localization of Windows Store apps

Localizing a Windows Store app is a fairly easy task thanks to the x:UId attribute introduced with WinRT.
If you need to create a Multilanguage application just add to your Visual Studio solution a folder named Strings and below it add a folder for each language you want to support using the two letter ISO language as name.
In this picture I have a solution that support Italian and American English


Inside each folder I’ve added a resource file and note that there’s a Resource.resw file just below Strings folder, it represent the default fallback resource language file that will be used in case your app will be executed on a system whose language is different than America English or Italian.

Inside each Resource.resw add the property of the control to localize, in our case we want to localize the Text property of a TextBlock, so the file content for each will be:

en-US folder


it-IT folder


Now to localize the Text property of our TextBlock all we need to to is use this XAML:

1 <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> 2 <TextBlock x:Uid="WelcomeMessage" 3 VerticalAlignment="Center" 4 Foreground="BlueViolet" 5 Text="..." 6 HorizontalAlignment="Center" 7 FontSize="48" /> 8 </Grid>

Here’s what you’ll see when the code is executed on an Italian pc:


Very easy isn’t it? Smile

This approach let you do more than just localize Text, if you want to dig more into it you can read this article

Ok, but imagine you have this mandatory requests:

  • 1-Application language can be unrelated to machine language (French app running on an Italian machine)

2-Language switching should not require an application reboot

3-You must use a MVVM friendly solution

Ok, things can get a little more intricate here  and since I haven’t found a standard solution I solved this way:

Step 1: Since we’ll deal with text only let’s rename resources inside .resw files from WelcomeMessage.Text to just WelcomeMessage (see below)


Step 2: Let’s create a ViewModel (yes, MVVM always requires a ViewModel…) and let’s add the necessary code to load the strings dynamically:

1 public class MyViewModel : INotifyPropertyChanged 2 { 3 private ResourceContext resoureContext; 4 5 public MyViewModel(string language) 6 { 7 this.UpdateCulture(language); 8 } 9 10 public void UpdateCulture(string language) 11 { 12 this.resoureContext = ResourceContext.GetForCurrentView(); 13 this.resoureContext.Languages = new List<string> { language }; 14 } 15 16 public string GetResource(string stringResource) 17 { 18 try 19 { 20 var resourceStringMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources"); 21 return resourceStringMap.GetValue(stringResource, this.resoureContext).ValueAsString; 22 } 23 catch (Exception ex) 24 { 25 return $"?{stringResource}?"; 26 } 27 } 28 29 ... 30 }

The magic here is inside UpdateCulture and GetResource methods, if we name the TextBlock in previous XAML snippet MyTextBlock we can dynamically change its text using this code:

1 public sealed partial class MainPage : Page 2 { 3 public MainPage() 4 { 5 this.InitializeComponent(); 6 this.MyTextBlock.Text = new MyViewModel("it-IT").GetResource("WelcomeMessage"); 7 8 } 9 }

But since we’re using MVVM we want to use databinding for that instead of code and we need a smart solution otherwise localization can become tedious, solution is not very far: just use an indexer:

Just add this line of code to the ViewModel

1 public string this[string key] => this.ApplicationController.GetResource(key);

And let’s inform binding that our indexer property need to be refreshed so that all texts will be reloaded when user changes the UI language at runtime modifying the UpdateCulture method this way:

1 public void UpdateCulture(string language) 2 { 3 this.resoureContext = ResourceContext.GetForCurrentView(); 4 this.resoureContext.Languages = new List<string> { language }; 5 this.OnPropertyChanged("Item[]"); 6 }

Note the trick of using “Item[]” as property name to signal that the class indexer has changed.

So let’s bind TextBlock’s Text property to viewmodel indexer using this syntax, and you’re done.

1 <TextBlock x:Name="MyTextBlock" 2 VerticalAlignment="Center" 3 Foreground="BlueViolet" 4 Text="{Binding [WelcomeMessage]}" 5 HorizontalAlignment="Center" 6 FontSize="48" />

You can find a complete example here.

Have fun!