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.

Cimbalino Toolkit 2.0.0-beta1

Assuming you don’t live in a planet where you don’t get internet (and I know that’s not the case as you’re reading this!), by now you know that Windows 10 has officially launched!

So did Visual Studio 2015 and NuGet 3.x, so pretty much everything you need to develop new Windows 10 universal apps, right? Not quite! ;)

Presenting the new and improved version 2.0.0-beta1 of the Cimbalino Toolkit, and as you already suspect, it is fully compatible with UWP (Universal Windows Platform)!

Proper kudos is owed to MVP Scott Lovegrove as he has done pretty good job for the last couple of weeks to get the toolkit up and running in Windows 10! :)

There is a breaking change on using the toolkit from previous versions: NuGet has removed the functionality of running Powershell scripts when you install a package, and Cimbalino Toolkit required that to add the Behaviors SDK to your projects… that said, please make sure that you manually add the Behaviors SDK to any project using the Cimbalino.Toolkit NuGet package!

On a final now, remember that this new version is still a beta as the code and documentation will be reviewed and tested during the next weeks, so do expect to find some issues and bugs! If you find any, please do report them directly on GitHub!

There’s never been a better time to be a Microsoft developer!

Full disclosure: though I’ve been a Microsoft employee for a short while, I currently have no professional (or other type of) connection with the company.

Now that we have got that out of the way, I do believe that there has never been a better time to be a Microsoft developer than today! :)

Ok, I’ll bite… why do you think that?

Microsoft Build Developers Conference was held last week in San Francisco. On it, Microsoft showed it’s vision for the future, and it is a bright one!

Though this article only scratches the surface on all that was shown, these were my personal highlights of the event!

Windows 10 everywhere!

Yes, Windows 10 will be everywhere, from PC’s, Laptops and Tablets, the Xbox One and Hololens, and also powering IoT devices like the Raspberry Pi 2.

For developers this translates in the fact that apps you develop for Windows 10, will also run in any other device! Functionality may obviously differ from device to device given their capabilities (touch screen on a tablet, augmented reality in Hololens, sensors on IoT devices, etc.), but in the end it will be the same Windows 10 app running on all of them!

Open-source initiative

The amount of code made available over the last couple of weeks in Microsoft’s GitHub page is truly astonishing!

Microsoft went from a closed-source software company to open-source a big chunk of their code in order to get contributions from the community (comments, reviews, code contributions, etc.), just like in any other GitHub repository!

Going cross-platform

Say goodbye to the Microsoft you’ve know for years as a Windows and Office only company; “Mobile first, cloud first” is the new motto, and there was enough proof of that in Build conference.

If you’re a web developer, you should definitely give Visual Studio Code a spin - and here’s the twist: it runs not only in Windows, but also in Mac and Linux, as Visual Studio Code is itself built on top of open-source technologies!

The whole CoreCLR (.NET Core Runtime) was built for Windows but now runs in Mac and Linux machines, meaning you can run the same .NET based code in all these platforms!

iOS and Android apps are welcome!

Develop apps for iOS or Android? Well, there’s some good news for you too: with Project Islandwood and Project Astoria, you’ll be able to make those apps run in Windows 10 with just a few modifications, and even sell them through the Windows Store and make some money out of it!

Targeting the Windows platform is definitely a smart move, as it will enable you to reach more users and increase potential revenue from your apps.

All apps are now Windows Apps

The “older” .NET and Win32 desktop apps we use all day long will now have a place in the Windows Store, making life easier for users to find, download and use them!

Just package those apps as a Windows 10 app, ship it to the store, and you’re done!

One more thing

Hololens! If you don’t know what it is by now, then you definitely should!!

While other companies are investing Virtual Reality, Microsoft took a different approach with Hololens and went with Augmented Reality.

As the name might suggest, “Augmented Reality” adds information to your real environment, and it’s usages are quite diverse. Microsoft showed a couple of demos of usage for construction and health that I believe made some jaw’s drop!

“DEVELOPERS, DEVELOPERS, DEVELOPERS!!”

No one said it, but I’m sure a lot of people remembered this while watching Build 2015:

https://www.youtube.com/watch?v=Vhh_GeBPOhs

Cimbalino Toolkit Documentation

The biggest request (and at the same time, the biggest complaint) I always had about Cimbalino Toolkit was to get some proper documentation about what the toolkit actually contains!

That has now changed, as the documentation is live at http://cimbalino.org/help

Cimbalino Toolkit Documentation

The whole documentation was generated from the inline XML Documentation with the help of SandCastle, so it’s still a bit minimum but I expect it to improve along time!

Please feel free to check it out and send some comments! :)

Windows 10 Technical Preview Tools now available!

In case you’ve missed it, Microsoft has now released the Windows 10 Technical Preview Developer Tools!

These allow you to start using the Windows 10 Universal Apps Platform (UAP) and thus developing apps for the next generation of Windows!

All you need is a machine (or VM) with the latest Windows 10 Preview and Visual Studio CTP 6 to install the developer tools preview and start building some awesome apps!! :)

Cimbalino Toolkit Windows 10 UAP support

I’ve been getting a lot of questions lately about Cimbalino Toolkit support for Windows 10 Apps (aka Universal Apps, UAP, Windows Apps, etc…)

I can assure you that support is definitely coming and you can get an early look on what is being done in Scott Lovegroove’s fork available here!

Cimbalino Toolkit: Integrating with MVVM Light Toolkit

Picking up where we left off on the previous article, you now know how to install the Cimbalino Toolkit in your app, so congratulations for that! :)

On this article I will show how to integrate it with the MVVM Light Toolkit, and then build a really simple “Hello World” app!

Note: Though this article will focus on how to integrate with the MVVM Light Toolkit, the Cimbalino Toolkit can be combined with most Windows development toolkits and frameworks that are available (like MVVMCross, Caliburn, etc.)

Using the same approach to add NuGet packages to the solution shown in the previous article, now search for “MvvmLight” and select the package shown in this picture:

Searching for MVVM Light Toolkit

You should now click on the Install button, confirm that you want to install the package into both projects, review the details shown in the License Acceptance window, and click the I Accept button.

You will now see a couple of warnings about moving the ViewModel folder manually; this is expected and it is due to the fact that we are building a Universal App (you can find more information about this here).

Look at the Solution Explorer Window, you should see that we have two ViewModel folders, one on each of the projects:

Projects with different ViewModel folders

Go ahead and delete one of the ViewModel folders, and move the remaining one from the project to the shared files on the bottom. The end result should look something like this:

Projects with shared ViewModel folder

We now we need to register the IMessageBoxService with the ViewModelLocator so that we can use it in the MainViewModel to show message popups in the app!

Edit the ViewModelLocator.cs file and change it to the following:

using Cimbalino.Toolkit.Services;
using GalaSoft.MvvmLight.Ioc;
using Microsoft.Practices.ServiceLocation;

namespace App1.ViewModel
{
    public class ViewModelLocator
    {
        public ViewModelLocator()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

            SimpleIoc.Default.Register<IMessageBoxService, MessageBoxService>();

            SimpleIoc.Default.Register<MainViewModel>();
        }

        public MainViewModel Main
        {
            get
            {
                return ServiceLocator.Current.GetInstance<MainViewModel>();
            }
        }

        public static void Cleanup()
        {
            // TODO Clear the ViewModels
        }
    }
}

As you can see above, we registered the IMessageBoxService with the MVVM Light Toolkit IoC Container by calling SimpleIoc.Default.Register<IMessageBoxService, MessageBoxService>(), and this is how we will use all of the services provided by Cimbalino Toolkit - and there are quite a lot of them!!

Now open the MainViewModel.cs file and change it to the following code:

using Cimbalino.Toolkit.Services;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;

namespace App1.ViewModel
{
    public class MainViewModel : ViewModelBase
    {
        private string _name;

        public string Name
        {
            get
            {
                return _name;
            }
            set
            {
                Set(ref _name, value);
            }
        }

        public RelayCommand SayHelloCommand { get; private set; }

        public MainViewModel(IMessageBoxService messageBoxService)
        {
            SayHelloCommand = new RelayCommand(async () => await messageBoxService.ShowAsync("Hello " + Name + "!"));
        }
    }
}

We started by adding a couple of properties, Name and SayHelloCommand, that we are going to bind to the view.

We can also see a IMessageBoxService parameter in the MainViewModel constructor, which the IoC Container will satisfy by creating an instance of MessageBoxService and providing it to the constructor.

Inside the constructor, we declared what will happen when the SayHelloCommand is invoked: show a popup message box with the input name.

That takes care of the view model, time to work on the view!

On the shared files project, create a new folder named View, and inside it create a new user control named MainUserControl.xaml with the following content:

<UserControl x:Class="App1.View.MainUserControl"
             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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             DataContext="{Binding Main,
                                   Source={StaticResource Locator}}"
             d:DesignHeight="300"
             d:DesignWidth="400"
             mc:Ignorable="d">

    <StackPanel>
        <TextBlock Text="name" />
        <TextBox Text="{Binding Name, Mode=TwoWay}" />
        <Button Command="{Binding SayHelloCommand, Mode=OneTime}" Content="Say Hello" />
    </StackPanel>
</UserControl>

For the view we will use root StackPanel control, containing a TextBlock with a “name” label, a TextBox binded to the Name property in the view model, and a Button binded to the SayHelloCommand property.

Notice also on the top of the file that we set the user control DataContext property to use the ViewModelLocator.Main property, which returns the instance of the MainViewModel.

Now all that we needed is to add our MainUserControl to the MainPage.xaml file in each of the app projects. In the end, each of the MainPage.xaml files should be similar to this:

<Page x:Class="App1.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:view="using:App1.View"
      mc:Ignorable="d">

    <Grid>
        <view:MainUserControl />
    </Grid>
</Page>

And… we are done!!!

Just run the Windows project and the Windows Phone project to confirm that our shared code does in fact work across the two platforms! :)

To make things even easier, you can download the full solution here!