Cimbalino Toolkit 2.2.0

Update: there was a packaging error in 2.2.0 which I already fixed and so the most current version is now 2.2.1!

Cimbalino Toolkit version 2.2.0 is now available!

This new version includes improved support for Windows Phone Silverlight 8.1 (WP81) so that developers can take advantage of its specific API’s (such as the FileOpenPicker)

This brings the total number of supported platforms to 5:

  • Windows Phone Silverlight 8.0 apps (WP8)
  • Windows Phone Silverlight 8.1 apps (WP81)
  • Windows Phone 8.1 apps (WPA81)
  • Windows Store 8.1 apps (Win81)
  • Windows 10 UWP apps (UAP)

Here’s the full change log for version 2.0.0:

  • Improved compatibility with Windows Phone Silverlight 8.1 (WP81)
  • New Cimbalino.Toolkit.Controls library (includes the HamburgerFrame for Windows 10)
  • New IFilePickerService to handle the file picker (when available)
  • Improvements over the INavigationService implementation
  • Other fixes and improvements

Cimbalino Toolkit Hamburger controls for UWP

Like it or not, the so called “Hamburger” design pattern has made its way to pretty much every platform, including the Windows Universal Apps!

Most Windows 10 native apps already show this new pattern, even a classic like the Calculator app!

However, for reasons unknown, Microsoft didn’t provide any Hamburger related control on the SDK base controls… frankly, this move brings back to memory when Windows Phone 7 SDK was launched without the Panorama and Pivot controls, the foundation of the whole “Metro” design guidelines!

The only alternative I’ve found is to use the Template 10, a “set of Visual Studio project templates”!

However, I’ve found that Template 10 version for Hamburger adds a bit of too much “fat” for my own taste, hence why I’ve been working on an alternative for the past last few weeks!

Introducing the Cimbalino Toolkit Controls

Starting with version 2.2.0 (currently still in beta 1), the Cimbalino Toolkit will feature a new package called Cimbalino.Toolkit.Control, and as the name suggests, it’s a control library for app developers.

Currently, the package features 3 controls:

  • HamburgerFrame
  • HamburgerTitleBar
  • HamburgerMenuButton

HamburgerFrame

Starting from the top, the HamburgerFrame control is a full replacement for the native Frame root control used in the app.xaml.cs file.

The control provides 3 content containers represented by the Header, SubHeader, and Pane properties, and on the center, it will show the navigated content:

HamburgerFrame container thumb

Obviously, you can specify content for this containers however you would like, or just leave them blank!

The Header allows content to be presented above the Pane, so it will never be hidden by it:

HamburgerFrame container thumb

The SubHeader allows content to be presented on the right side of the Pane. This means that if the pane is in one of the “overflow” modes it will show on top of this container, hiding the content behind it:

HamburgerFrame container thumb

The control also provides background properties for all these containers (HeaderBackground, SubHeaderBackground, and PaneBackground).

To make the life easier of developers, I’ve “borrowed” the VisualStateNarrowMinWidth, VisualStateNormalMinWidth, and VisualStateWideMinWidth properties from Template 10, which allow to specify the break points where the pane state and location will readjust. If you don’t want to use these, you can always do it manually with the exposed pane related properties (IsPaneOpen, DisplayMode, OpenPaneLength, CompactPaneLength, …).

HamburgerTitleBar

The HamburgerTitleBar control provides a basic Hamburger button on the left side (can be hidden with the MenuButtonVisibility property), and a Title property.

HamburgerTitleBar

This is a quite rudimentar and easy to use control, yet developers might want to just go ahead and create their own version of this control and place it on their apps!

HamburgerMenuButton

Finally, the HamburgerMenuButton is the button you’ll be using in the pane to indicate the available menu options!

This control shows a left-side icon and an optional label (through the Icon and Content properties):

HamburgerMenuButton basic states

The regular approach here will be to just place all the HamburgerMenuButton controls inside a vertical StackPanel, but one can also stack them horizontally, and in this case, we would only show the icon and hide the label (using the provided LabelVisibility property).

The NavigationSourcePageType property allow developers to specify the destination page type for navigation purposes. If the property is set, the button will automatically highlight anytime the page is the frame current navigation content.

So how can I use these in my app?

First step is to add the Cimbalino.Toolkit.Controls NuGet package to the project!

Then, create a new user control to define your menu; in it, add as many HamburgerMenuButton instances as the number of options you want to present!

Here’s how your menu might look like:

<UserControl x:Class="App1.View.HamburgerPaneControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="using:Cimbalino.Toolkit.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:view="using:App1.View"
d:DesignHeight="300"
d:DesignWidth="400"
mc:Ignorable="d">

<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>

<StackPanel>
<controls:HamburgerMenuButton Content="Home" NavigationSourcePageType="view:MainPage">
<controls:HamburgerMenuButton.Icon>
<FontIcon FontSize="16" Glyph="& #xE80F;" />
</controls:HamburgerMenuButton.Icon>
</controls:HamburgerMenuButton>

<controls:HamburgerMenuButton Content="Details" NavigationSourcePageType="view:DetailsPage">
<controls:HamburgerMenuButton.Icon>
<FontIcon FontSize="16" Glyph="& #xE8BC;" />
</controls:HamburgerMenuButton.Icon>
</controls:HamburgerMenuButton>
</StackPanel>

<controls:HamburgerMenuButton Grid.Row="1"
Content="Settings"
NavigationSourcePageType="view:SettingsPage">
<controls:HamburgerMenuButton.Icon>
<FontIcon FontSize="16" Glyph="& #xE713;" />
</controls:HamburgerMenuButton.Icon>
</controls:HamburgerMenuButton>
</Grid>
</UserControl>

Next, open the app.xaml.cs file and replace this line:

rootFrame = new Frame();

with this:

rootFrame = new Cimbalino.Toolkit.Controls.HamburgerFrame()
{
Header = new Cimbalino.Toolkit.Controls.HamburgerTitleBar()
{
Title = "App1"
},
Pane = new View.HamburgerPaneControl()
}

Congratulation: your app now has a universal Hamburger menu with a nice title bar! :)

App with HamburgerFrame

Next steps might be to create a separate user control to hold the HamburgerTitleBar, which will then allow you to bind the Title property to view model (making it easier to update on a page by page basis).

To make things easier, I’ve provided the source code for a simple app using these controls!

Still Strong-Naming your Assemblies? You do know it's 2016, right?

Update: Though the information and concerns in this blog post are still very true, I’ve actually had a change of heart and I’m now advocating to Start Strong-Naming your Assemblies!!


For far to long, Strong-Named Assemblies have been a huge rock in the shoe of 3rd party library developers, but people: it’s 2016, so why are you still using it?

How it all started…

The year was 2002 (or so I believe!), Microsoft had just released the .NET Framework, and one of the main enterprise focused features was the ability to sign an assembly with a strong-name.

Back then, Strong-Named Assemblies had some great advantages, as indicated in this MSDN article:

  • You want to enable your assemblies to be referenced by strong-named assemblies, or you want to give friend access to your assemblies from other strong-named assemblies.
  • An app needs access to different versions of the same assembly. This means you need different versions of an assembly to load side by side in the same app domain without conflict. For example, if different extensions of an API exist in assemblies that have the same simple name, strong-naming provides a unique identity for each version of the assembly.
  • You do not want to negatively affect performance of apps using your assembly, so you want the assembly to be domain neutral. This requires strong-naming because a domain-neutral assembly must be installed in the global assembly cache.
  • When you want to centralize servicing for your app by applying publisher policy, which means the assembly must be installed in the global assembly cache.

So strong-named assemblies are uniquely identified, which is a good thing, until it starts to work against you…

Let’s look at a real example: a few years back, JSON.net was actually a strongly-signed assembly. Now let’s assume we have a project that depends on “LibraryA” and “LibraryB”, and each of these require a different version of JSON.net.

Before Assembly Binding Redirection
Before Assembly Binding Redirection

If you build the project as it currently is, there will be a conflict as you can only have a single version of JSON.net on the output folder, but the libraries require different versions…

To fix this issue, .NET provided a mechanism called Assembly Binding Redirection to ensure that only one specific assembly would be used, regardless of the required version.

After Assembly Binding Redirection
After Assembly Binding Redirection

In comes Silverlight and Windows Phone

Unfortunately, neither Silverlight nor Windows Phone support Assembly Binding Redirection… and that is where the true problems started.

There are quite a few threads around this issue over the internet, and in the end, a lot of 3rd party library developers just decided to stop strong-naming their assemblies!

Others, followed the advice of the MSDN article I pointed above:

If you are an open-source developer and you want the identity benefits of a strong-named assembly, consider checking in the private key associated with an assembly into your source control system.

Obviously, for this to work you would have to build your own versions of your project dependencies… and let’s be honest here: that will eventually be more of a problem that a solution.

A few years ago, I personally felt this pain while developing a Windows Phone app, and so I went to the Windows Phone Developers UserVoice website and requested the support for Assembly Binding Redirection on Windows Phone… almost a year after the request, I got an update indicating it was “on the backlog”, and seems it has stayed like that till now…

If it is such a bad thing, why are people still doing it?

Developers seem to have the wrong notion that they should strong-name their assemblies as a security feature, but this could not be further away from the truth!

Granted, that does provide a basic insurance that an assembly hasn’t been tampered/altered, but in any case one can always use binding redirection (when available) to bypass the whole thing, so that is just a lame excuse to not buy a proper Code Signing Certificate and apply Authenticode to the assembly (which will prevent tampering AND impersonation, the right way!).

What about the Universal Windows Platform?

Unfortunately, as far as I know there is no support for Assembly Binding Redirection in UWP

A couple of weeks ago, Microsoft open-sourced the XAML Behaviors and guess what? Yes you guessed correctly: they strongly-signed it!

Fortunately, after a long debate on that same thread, they realized that it made no sense to do that, and removed the strong-name signing on the latest version!

Bottom line

With this article I tried to make the point that Strong-Named Assemblies are just legacy of the “old” .NET Framework days, and have no place in the modern Universal Windows Platform.

Hopefully, 3rd party developers will continuously provide non-strongly-named assemblies which will make a lot of developers happy.

XAML Behaviors UWP Managed 1.1.0

The XAML Behaviors for UWP has just been updated to version 1.1.0.

Among other changes, this version contains two fixes that I personally contributed for issues found in the EventTriggerBehavior:

The NuGet package has been updated so if you’re using the Xaml Behaviors in your app, all you need is to let NuGet take the latest version of the package!

In the next days I’ll be releasing a new version of the Cimbalino Toolkit to take this updated Xaml Behaviors package.

Update 24/02/2016:

I forgot to mention a massive difference on the new version of the XAML Behaviors:

If you use PowerShell to output the Assembly Full Name from the current and previous versions of the XAML Behaviors, this is what you will get:

Microsoft.Xaml.Interactivity assembly full name

Notice the different PublicKey value?

Well, after a long discussion about it, seems Microsoft has finally decided in removing the StrongName signing!

Though this might not sound as an important change, it is fundamentally a sign of ditching the “old” legacy .NET Framework stuff.

But I’ll leave that for a next post… ;)

Awaiting the CoreDispatcher

Most programming language allow you to take advantage of multi-threaded execution, and .NET is no exception!

Asynchronous code is a modern abstraction of multi-threading execution, and as you hopefully are aware, in .NET land, this is achieved with the async and await keywords.

For the Universal Windows Platform, we can also count on the CoreDispatcher class to marshal execution back to the main thread, from which we can update the UI of our apps.

Here’s a simple example of how to use it:

public async void DoStuff()
{
var dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;

await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
UpdateUI();
});

DoOtherStuff();
}

Assuming we are on a background thread when the DoStuff() method is invoked, we will retrieve a CoreDispatcher instance from the CoreWindow.CoreDispatcher property, call and await for the execution of dispatcher.RunAsync() method, which in turn will invoke the UpdateUI() method on the main thread, and then code execution will continue in the background thread by invoking the DoOtherStuff() method.

As it is right now, we know that DoOtherStuff will only execute after the UpdateUI() method finishes, but now let’s assume that we replace the UpdateUI() synchronous method with an asynchronous version of it, called UpdateUIAsync():

public async void DoStuff()
{
var dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;

await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
await UpdateUIAsync();
});

DoOtherStuff();
}

In this new version of the code, you’ll notice that the DoOtherStuff() method will eventually run before the UpdateUIAsync() has finished, which might not be what you intended to in the first place when you await’ed for the dispatcher.RunAsync() method!

This is due to the fact that the CoreDispatcher.RunAsync method has a DispatchedHandler callback which is not asynchronous:

public delegate void DispatchedHandler()

The fact that we’ve added the async/await keywords to the callback doesn’t ensure that the caller will await for it to execute!

There are a few ways suspend the background thread execution until the foreground thread signals for it to continue, and using a TaskCompletionSource<T> is one of the easiest:

public async void DoStuff()
{
var dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;
var taskCompletionSource = new TaskCompletionSource<bool>();

await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
await UpdateUIAsync();

taskCompletionSource.SetResult(true);
});

await taskCompletionSource.Task;

DoOtherStuff();
}

In this version of the code, once the execution returns from await’ing the dispatcher.RunAsync() call, the background thread will carry on execution, but will then await for the taskCompletionSource.Task to finish, which will only happen after the taskCompletionSource.SetResult(true) call that we make in the main thread!

I’ve written a few CoreDispatcher extension methods to help around this issue, and added them to the next version of the Cimbalino Toolkit, but you can access them right now if you wish so! ;)

Compiled Bindings considerations II

Update: Microsoft has finally provided a fix for this bug, covered in the Compiled Bindings considerations III article!

A few months ago I wrote my first Compiled Bindings considerations article, and seems that time has come to write some more, only this time I’m bearer of some bad news…

TL;DR

Compiled Bindings have a bug, noticeable in some scenarios, specifically when a binding has a fallback value of null (which is the default)!

Make sure to thoroughly test your app if you use compiled bindings!

So what is the big deal?

To illustrate the problem, I’ve written a small demo app!

Let’s start by checking the view models code:

public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}

public class MainViewModel : ViewModelBase
{
private CurrentTimeViewModel _currentTime;

public CurrentTimeViewModel CurrentTime
{
get { return _currentTime; }
set
{
_currentTime = value;
OnPropertyChanged();
}
}
}

public class CurrentTimeViewModel : ViewModelBase
{
private string _currentTimeTicks;

public string CurrentTimeTicks
{
get { return _currentTimeTicks; }
set
{
_currentTimeTicks = value;
OnPropertyChanged();
}
}

public CurrentTimeViewModel()
{
Update();
}

public void Update()
{
CurrentTimeTicks = DateTime.Now.Ticks.ToString();
}
}

Our view model is composed of 3 classes:

  • ViewModelBase is just a standard implementation for the INotifyPropertyChanged interface, providing an OnPropertyChanged helper method to its inheritors.
  • MainViewModel will be used as the main view model for our sample and has a single property, CurrentTime.
  • CurrentTimeViewModel has a single CurrentTimeTicks property which will contain a string representing the current time in ticks; an Update helper method has also been added to this view model.

Now let’s take a look at the MainPage view:

<Page x:Class="CompiledBindings2.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="using:CompiledBindings2"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>

<StackPanel Margin="12">
<TextBlock Style="{StaticResource CaptionTextBlockStyle}" Text="Current Time Ticks (Binding)" />
<TextBlock Style="{StaticResource BodyTextBlockStyle}" Text="{Binding CurrentTime.CurrentTimeTicks}" />

<TextBlock Style="{StaticResource CaptionTextBlockStyle}" Text="Current Time Ticks (x:Bind)" />
<TextBlock Style="{StaticResource BodyTextBlockStyle}" Text="{x:Bind ViewModel.CurrentTime.CurrentTimeTicks, Mode=OneWay}" />
</StackPanel>

<StackPanel Grid.Row="1">
<Button HorizontalAlignment="Stretch"
Click="CreateChildViewModelButton_OnClick"
Content="Create CurrentTimeViewModel" />
<Button HorizontalAlignment="Stretch"
Click="UpdateCurrentTimeViewModelButton_OnClick"
Content="Update CurrentTimeViewModel" />
<Button HorizontalAlignment="Stretch"
Click="DestroyCurrentTimeViewModelButton_OnClick"
Content="Destroy CurrentTimeViewModel" />
</StackPanel>
</Grid>
</Page>

The MainPage view is composed of the following:

  • a TextBlock with its Text property binded to CurrentTimeViewModel.CurrentTimeTicks, using “classic” bindings
  • a TextBlock with its Text property binded to CurrentTimeViewModel.CurrentTimeTicks, using compiled bindings
  • a Button to create a new CurrentTimeViewModel instance
  • a Button to update the current CurrentTimeViewModel instance
  • a Button to destroy the current CurrentTimeViewModel instance

Finally, here’s the code behind for the MainPage view:

public sealed partial class MainPage : Page
{
private readonly MainViewModel _viewModel;

public MainPage()
{
this.InitializeComponent();

_viewModel = new MainViewModel();

this.DataContext = _viewModel;
}

public MainViewModel ViewModel
{
get { return _viewModel; }
}

private void CreateChildViewModelButton_OnClick(object sender, RoutedEventArgs e)
{
_viewModel.CurrentTime = new CurrentTimeViewModel();
}

private void UpdateCurrentTimeViewModelButton_OnClick(object sender, RoutedEventArgs e)
{
if (_viewModel.CurrentTime != null)
{
_viewModel.CurrentTime.Update();
}
}

private void DestroyCurrentTimeViewModelButton_OnClick(object sender, RoutedEventArgs e)
{
_viewModel.CurrentTime = null;
}
}

As you can see above, we create a new MainViewModel instance, set it as the page DataContext property, and then we have the three click event handlers, one for each of the buttons on the view.

We’ve also added a MainPage.ViewModel property to expose the current MainViewModel instance to the compiled bindings (we can’t use the DataContext property as its type is object and compiled bindings require strong-typed properties to work).

This is what you’ll get if you run the app and tap the buttons in succession:

Compiled Bindings FallbackValue bug

As you can see, the 2nd TextBlock (the one using compiled bindings) never gets the text cleared when we tap the “Destroy CurrentTimeViewModel” button!

The expected behavior is the one shown in the 1st TextBlock: if the binding value is null or unavailable, the TextBlock.Text property will set to the Binding.FallbackValue (which is null by default).

So after checking the documentation for compiled bindings, one can say without that compiled bindings are ignoring the fallback value when its value is null, and that is quite a nasty bug in the compiled bindings!

This bug has already been reported to Microsoft but as we don’t know when it will get fixed, all we can do right now is be aware of the whole issue and make sure to test our apps thoroughly to ensure we don’t end up with these problems after migrating to compiled bindings!

Paying the tab for .NET Native

.NET Native behaves just like that expensive restaurant you love to got to: you have to wait until you finish the meal to see how much it will cost you - and it will definitely cost you!

Last weekend I was confronted with a bug in Cimbalino Toolkit MultiBindingBehavior, which caused apps using it to crash when they were built in Release mode!

I built a small test app and after a couple of minutes debugging it I noticed a MissingMetadataException getting raised; the culprit was found: .NET Native!

If you’re working with Universal Windows Apps (UWP) and don’t know what .NET Native is, I strongly advise you to start by reading the following excellent articles written by Morgan Brown, “a Software Development Engineer on the .NET Native team”:

Here’s the situation right now: when you build a UWP app, the compiler will do some “smart stuff” with your code (let’s skip the technicals here!), squeezing every little bit it can to make sure the compiled result will perform better and faster!

But there is a catch: if your code uses any type of dynamic coding features such as reflection or serialization, you might need to instruct the compiler that certain types in your application will be used as such, in order to avoid the exceptions like the MissingMetadataException you see above.

To avoid such problems, you can add specially built rd.xml files to your project - once again, check the articles above for more information on this subject!

The MultiBindingBehavior works by using the AssociateObject property value to reflect and dynamically create a binding expression, so what I needed was to ensure that it would be able to reflect any object passed to this property.

With this requirement in mind, I created a new Cimbalino.Toolkit.rd.xml file, set its Build Action to Embedded Resource, and set the content to the following:

<?xml version="1.0" encoding="utf-8"?>
<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
<Library Name="Cimbalino.Toolkit">
<Type Name="Cimbalino.Toolkit.Behaviors.MultiBindingBehavior">
<Property Name="AssociatedObject" Serialize="Included" />
</Type>
</Library>
</Directives>

Aaand… this didn’t work! I started getting a build error message stating that it couldn’t find any AssociatedObject property in the Cimbalino.Toolkit.Behaviors.MultiBindingBehavior.

Granted, the property does not exist directly in this class, but rather in the Behavior<T> base class, so I guess one say that .NET Native compilation completely forgot a completely basic feature of .NET and most object oriented languages: Class Inheritance!

Taking this into account, I made a couple of changes in the file and here’s what in the end made it work:

<?xml version="1.0" encoding="utf-8"?>
<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
<Library Name="Cimbalino.Toolkit" />
<Library Name="Microsoft.Xaml.Interactions">
<Type Name="Microsoft.Xaml.Interactivity.Behavior{T}">
<Property Name="AssociatedObject" Serialize="Included" />
</Type>
</Library>
</Directives>

So here’s what I learned in the past weekend:

  • When working with Universal Windows Apps, make sure to build the app in Release mode and test it thoroughly!
  • Keep an eye out on the build warnings for any problems with your rd.xml files.
  • If you’re working with MVVM or have Model representation classes, it might make sense to put these in a separate assembly, or at least in a separate namespace from the rest of the code - this will allow you to easily target these files in a rd.xml for .NET Native optimization exclusion.

XAML Behaviors now open source and on UWP

In case you missed the big news, the XAML Behaviors are now open source in GitHub and available to use in UWP, both in managed and native apps, mostly due to the work of some awesome MVPs!

They were kind enough to keep me in the loop and that allowed me to prepare for the incoming changes! ;)

Cimbalino Toolkit 2.1.0

Version 2.1.0 of the Cimbalino Toolkit is a basic update of the toolkit with a few improvements and bug fixes, but takes into account the new XAML Behaviors:

  • UWP apps it now will pull the XAML Behaviors Managed NuGet package to the projects
  • non-UWP apps will still use the NuGet PowerShell scripts to add the Behaviors SDK

A few weeks ago I introduced the MonitoredInteraction class from Cimbalino Toolkit 2.0.0 to “prevent memory leaks in behaviors”, and I’m happy to say that those changes made it’s way to the XAML Behaviors code! :)

Do notice that while the Interaction class in the XAML Behaviors now performs the proper attach/detach pattern, the same can’t be said for the Behaviors SDK Extension for non-UWP apps, so I strongly advise you to keep using the MonitoredInteraction class for those projects!

One final note: if you actually want to use the XAML Behaviours, you will have to actually manually add the NuGet package to your project… this is due to the new Transitive Dependencies feature of NuGet 3.x, and as far as I know, there is no way of going around this extra step!