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

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 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

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!

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!

How to prevent memory leaks in Behaviors

Attached Behaviors have been around for quite a while, and though I personally always liked them, they have a fundamental flaw: they can lead to huge memory leaks!

I’ve seen quite a few fixes for them (like this one from MVP Joost Van Schaik), though none proved to be truly “universal” and final!

To demonstrate the problem, let’s take a practical example:
– create an app with two pages
– page 1 will have a button to navigate to page 2
– page 2 will have a button that when clicked, will navigate back to page 1 after a pause of 2 seconds

Here’s the view model for page 2, Page2ViewModel:

public class Page2ViewModel
{
    public event EventHandler GoBack;

    public ICommand DelayedGoBackCommand { get; private set; }

    public MainViewModel()
    {
        DelayedGoBackCommand = new CustomCommand(OnDelayedGoBackCommand);
    }

    private async void OnDelayedGoBackCommand()
    {
        await Task.Delay(2000);

        GoBack?.Invoke(this, EventArgs.Empty);
    }
}

The code is really simple: when the DelayedGoBackCommand gets invoked, we will make a 2 seconds pause, and then raise the GoBack event.

Now lets say that all view models have been registered as singletons in the App class, something like this:

sealed partial class App : Application
{
    public static Page2ViewModel Page2ViewModel { get; } = new Page2ViewModel();

    // remaining code
}

This is the code behind for page 2, where we will set the page view model:

public class Page2
{
    public Page2()
    {
        InitializeComponent();

        DataContext = App.Page2ViewModel;
    }
}

And this is the view we will be using for page 2:

<Page x:Class="MyApp.Page2"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:core="using:Microsoft.Xaml.Interactions.Core"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:i="using:Microsoft.Xaml.Interactivity"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      x:Name="PageRoot"
      mc:Ignorable="d">

    <StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <i:Interaction.Behaviors>
            <core:EventTriggerBehavior EventName="GoBack"
                                       SourceObject="{Binding}">
                <core:CallMethodAction MethodName="GoBack"
                                       TargetObject="{Binding Frame,
                                                              ElementName=PageRoot}" />
            </core:EventTriggerBehavior>
        </i:Interaction.Behaviors>

        <Button Command="{Binding DelayedGoBackCommand,
                                  Mode=OneTime}"
                Content="Go Back" />
    </StackPanel>
</Page>

As you can see above, the button is binded to the Page2ViewModel.DelayedGoBackCommand. Also, we will be using an EventTriggerBehavior to monitor the Page2ViewModel.GoBack event, and when it gets raised, we will use the CallMethodAction to invoke the Page2.Frame.GoBack method.

Now here’s the catch: while behaviors have a way of being notified when they are to be detached, that never happens!! Not when you leave the page, not when the page gets unloaded, and not even when garbage collection runs.

As such, when we navigate back from page 2, Page2ViewModel.GoBack event will still hold a reference to the EventTriggerBehavior, leading to a memory leak!

But things get even worse in this example: everytime we navigate to page 2, we will subscribe over and over again the GoBack event, so multiple invocations will eventually occur – definitely not what we wanted!

Introducing the MonitoredInteraction class

The Cimbalino Toolkit now has the MonitoredInteraction class to solve this issue!

The MonitoredInteraction was built as a direct replacement of the Microsoft.Xaml.Interactivity.Interaction, and will monitor the attached object Loaded and Unloaded events and call for the attachment and detachment of all behaviors it contains!

Here’s how page 2 view would look if put it to use:

<Page x:Class="MyApp.Page2"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:core="using:Microsoft.Xaml.Interactions.Core"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:behaviors="using:Cimbalino.Toolkit.Behaviors"
      x:Name="PageRoot"
      mc:Ignorable="d">

    <StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <behaviors:MonitoredInteraction.Behaviors>
            <core:EventTriggerBehavior EventName="GoBack"
                                       SourceObject="{Binding}">
                <core:CallMethodAction MethodName="GoBack"
                                       TargetObject="{Binding Frame,
                                                              ElementName=PageRoot}" />
            </core:EventTriggerBehavior>
        </behaviors:MonitoredInteraction.Behaviors>

        <Button Command="{Binding DelayedGoBackCommand,
                                  Mode=OneTime}"
                Content="Go Back" />
    </StackPanel>
</Page>

Really, really simple, yet it will finally ensure that behaviors do get detached when one navigates away of a page, and re-attached when navigating in!

Hopefully someone from the Behaviors SDK team will read this, and take some of the suggestions here to fix this well known issue that’s been around for quite a while! 😉

Compiled Bindings considerations

As you’re probably aware, Windows 10 introduced a new type of Bindings called Compiled Bindings.

And as the name might suggest, compiled bindings are a way the compiler uses to generate static code for a binding instead of using a reflection based solution, as regular bindings do.

The main advantage is quite obvious: there will be a performance gain for using static compiled code instead of using reflection!

Let’s take a look at a simple regular binding example:

<TextBlock Text="{Binding Name}" />

This binding will set the TextBlock.Text property to the value of the Name and will update it every time the Name property changes (assuming that the data context implements and raises the necessary INotifyPropertyChanged.PropertyChanged event)

To take advantage of the compiled bindings, one would rewrite it like this:

<TextBlock Text="{x:Bind Name, Mode=OneWay}" />

Notice that I added the Mode=OneWay on the expression above?

Well, that is actually required due to a fundamental difference between regular bindings and compiled bindings: while the regular bindings default mode is OneWay, compiled bindings default mode is OneTime!

This is a really important piece of information that I’ve seen a lot of developers not taking notice, so make sure to fix those binding expressions correctly when you migrate to compiled bindings!

Cimbalino Toolkit 2.0.0 (final)

Bring out the champagne, because Cimbalino Toolkit version 2.0.0 has gone “gold” and is now production ready! 🙂

As previously stated, the focus for this new version was to add support for UWP (Universal Windows Platform), thus making the toolkit support a total of 4 platforms:

  • Windows Phone Silverlight 8.0 and 8.1 apps (WP8)
  • Windows Phone 8.1 apps (WPA81)
  • Windows Store 8.1 apps (Win81)
  • Windows 10 UWP apps (Universal Windows Platform)

Please remember to manually add the Behaviors SDK to your UWP apps if you use Cimbalino! The other platforms will have it added automatically, but due to changes in the way NuGet works this is not possible for UWP.