The AbandonedMutexException hoax!

When working with multi-process applications, there comes a time where you’ll definitely need some sort of synchronization, and for that specific purpose we have the Mutex class.

MSDN states the following for the Mutex class:

When two or more threads need to access a shared resource at the same time, the system needs a synchronization mechanism to ensure that only one thread at a time uses the resource. Mutex is a synchronization primitive that grants exclusive access to the shared resource to only one thread. If a thread acquires a mutex, the second thread that wants to acquire that mutex is suspended until the first thread releases the mutex.

Bottom line is that the mutex is a system wide lock, not just contained to the current process!

When it comes to usage, there is a major difference between them: the lock keyword is used to contain a thread-safe block of code, and when code is executed outside of that block, the locked object is released; the mutex on the other hand, doesn’t use the same approach, and as such has to manually be released.

One situation that you can get into is when a thread terminates while owning a mutex, the mutex is said to be abandoned, and this is a really bad thing, normally indicating a serious programming error.

Unfortunately, due to the volatile nature of the Windows Phone background agents, abandoned mutexes will eventually happen without any thing a developer can actually do, but to catch and treat the AbandonedMutexException that will get raised on the other awaiting thread (if one exists)!

The following code sample simulates how to raise and handle the AbandonedMutexException:

public static void MutextTest()
{
    var mutex = new Mutex(false, "MyMutex");

    new Thread(() =>
    {
        mutex.WaitOne();

        Thread.Sleep(1000);
    }).Start();

    Thread.Sleep(2000);

    try
    {
        mutex.WaitOne();
    }
    catch (AbandonedMutexException e)
    {
        Debug.WriteLine(e);
    }
    catch (Exception e)
    {
        Debug.WriteLine(e);
    }
}   

When running the above in a Console application, this is the output we get from it:

System.Threading.AbandonedMutexException: The wait completed due to an abandoned mutex.

For the same code in a Windows Phone 8 app, this will be the output:

System.Exception: The wait completed due to an abandoned mutex.

The two platforms show an inconsistent result for the same behavior, as an AbandonedMutexException get thrown for the full .NET Framework, and a generic Exception for the WP8 one.

Seems that the only thing in common is actually the message!…

One interesting fact is that the Mutex documentation for WP8 does not mention the AbandonedMutexException class, though it does exist in the WP8 class library, but doesn’t seem to be in use anywhere on the platform. This may be the result of having similar behavior as the WP7 platform, where we would actually get the same behaviour due to the lack of the more specific AbandonedMutexException class.

Cimbalino Windows Phone Toolkit Updated to v3.0.0

I’m proud to present the latest version of Cimbalino Windows Phone Toolkit!

This new version comes with a major breaking change: Visual Studio 2012 is now required, as the toolkit has taken the “async/await” path! :D

If you still use Visual Studio 2010 for your Windows Phone development, you can still use the previous version of the toolkit (but then again, seems like a really nice time to upgrade ;) )

And without further ado, here’s the change-log:

  • async/await support added for WP7
  • New Cimbalino.Phone.Toolkit.Background component, fully compatible with Background Agents.
  • New ShellTileService
  • New VoiceCommandService
  • New LauncherService
  • New NetworkInformationService
  • AsyncStorageService is now compatible with WP7
  • BingMapsService has been removed and the functionality moved to MapsService
  • Several improvements and bug fixes!

Review of my WPUG talk

Last Monday I had the pleasure of participating in a WPUG event where I talked about the Nokia Music API and the Cimbalino Windows Phone Toolkit.

I had quite a technical challenge, as I couldn’t access the internet from inside the emulator, no matter what I did!

After a couple of minutes in silent panic, I tried to bypass the connectivity problems the best I could, doing anything from showing a YouTube video of Nokia Music features to running the demos on my personal phone and showing it off in the air to the audience!

Other than that, the event went really good, and hopefully I’ll start seeing more and more people using the Nokia Music API and Cimbalino Windows Phone Toolkit in their apps! ;)

From the feedback I got, I can see people requesting more information about MVVM, so I’m going to point to two articles I wrote about two years ago for Coding4Fun (now part of Microsoft Channel9):

My big “thank you” to Matt Lacey and Riaz Ahmed for the opportunity! :)

Cimbalino Windows Phone Toolkit: MultiBindingBehavior

One of the features I most enjoy in WPF is the MultiBinding class, which allows you to take several source properties, pass their values to an IMultiValueConverter implementation, and bind the result to a single target property!

By now you’re probably thinking “why do I need that?”, but in certain specific scenarios, having the possibility to take several values and produce a single result directly in the UI can be quite useful!

Take this sample from MSDN:

<TextBlock DataContext="{StaticResource NameListData}">
  <TextBlock.Text>
    <MultiBinding Converter="{StaticResource myNameConverter}"
                  ConverterParameter="FormatLastFirst">
      <Binding Path="FirstName"/>
      <Binding Path="LastName"/>
    </MultiBinding>
  </TextBlock.Text>
</TextBlock>

We can easily infer that the objective here is to set the TextBlock.Text property to the result of “LastName, FirstName”, given the two properties from the specified TextBlock.DataContext and a custom IMultiValueConverter instance called myNameConverter.

While useful, the MultiBinding is not available for Windows Phone developers - queue the whining…

I’ve seen a few alternative implementations around the internet, but none seems easy (and light!) enough to me, so I just decided to make my own!

On the latest release of Cimbalino Windows Phone Toolkit I added the MultiBindingBehavior, a quick and easy approach to solve the missing MultiBinding support in Windows Phone!</p>

Here’s an example using the same scenario from above:

<TextBlock DataContext="{StaticResource NameListData}">
    <i:Interaction.Behaviors>
        <cimbalinoBehaviors:MultiBindingBehavior Converter="{StaticResource myNameConverter}" ConverterParameter="FormatLastFirst" PropertyName="Text">
            <cimbalinoBehaviors:MultiBindingItem Value="{Binding FirstName}" />
            <cimbalinoBehaviors:MultiBindingItem Value="{Binding LastName}" />
        </cimbalinoBehaviors:MultiBindingBehavior>
    </i:Interaction.Behaviors>
</TextBlock>

The major difference here is the usage of MultiBindingBehavior.PropertyName, as we can’t bind the target property directly, it will be up to the behavior to get/set the value. All the rest of the code is really quite self explanatory!

Here’s another sample using two TextBox controls to input the FirstName and LastName values:

<TextBox x:Name="FirstNameTextBox" />
<TextBox x:Name="LastNameTextBox" />
<TextBlock Style="{StaticResource PhoneTextLargeStyle}">
    <i:Interaction.Behaviors>
        <cimbalinoBehaviors:MultiBindingBehavior Converter="{StaticResource myNameConverter}" ConverterParameter="FormatLastFirst" PropertyName="Text">
            <cimbalinoBehaviors:MultiBindingItem Value="{Binding Text, ElementName=FirstNameTextBox}" />
            <cimbalinoBehaviors:MultiBindingItem Value="{Binding Text, ElementName=LastNameTextBox}" />
        </cimbalinoBehaviors:MultiBindingBehavior>
    </i:Interaction.Behaviors>
</TextBlock>

You can set the MultiBindingBehavior.Converter property to any IValueConverter instance (knowing that the value parameter is always an object[] instance) but I’ve also added an abstract MultiValueConverterBase that you can inherit and implement quite easily!

WPUG London meeting 20 May: Nokia Music & demo showcase

I’m happy to confirm that my first presentation in the UK will be for the WPUG May 20 event.

I’ll be talking about the Nokia Music API and the Nokia Music app, but you can also count on some good info on the Cimbalino Windows Phone Toolkit!

The event venue is Nokia’s office in Paddington, London, and registration is free and required!

Cimbalino Windows Phone Toolkit updated to v2.3.0

I just released a new Cimbalino Windows Phone Toolkit version!

Here’s a short list of all the goodies you’ll find in the 2.3.0 version:

  • Breaking change: Location component now uses the new Windows Phone 8 Location API (Geolocator) on WP8 (WP7 version will mimic behavior with GeoCoordinateWatcher)
  • Breaking change: In WP8, the UserExtendedPropertiesService.AnonymousUserID now returns the “ANID2” value (WP7 version will still return “ANID”)
  • New MultiBindingBehavior
  • New OptimizedObservableCollection class
  • Several improvements and bug fixes!

I didn’t actually release a change log for the previous 2.2.0 version, so here it is now:

  • New MutexLock and NamescopeBinding helper classes
  • New BooleanToBrushConverter and BooleanToIntConverter
  • New UriExtensions class
  • The ApplicationBarBehavior and MultiApplicationBarBehavior can now be attached to the PhoneApplicationPage
  • The SystemTrayService implementation now allows for a global system tray across all pages
  • Removed the cimbalino = http://cimbalino.org XML namespace prefix (incompatible with WP8)
  • Several improvements and bug fixes

A big “thank you” is due to Scott Lovegrove for his continuous code contributions and articles about the toolkit!

Now to write some posts about the new features… ;)

Understanding XAML Namescopes

I’ve been getting some inquires about the BindableApplicationBar sample from the Cimbalino Windows Phone Toolkit, specifically about what is the NamescopeBinding resource appearing on the top of the MainPage.xaml file.

Here is the specific bit:

<phone:PhoneApplicationPage.Resources>
    <cimbalinoHelpers:NamescopeBinding x:Key="ItemsMultiselectList" Source="{Binding ElementName=ItemsMultiselectList}" />
</phone:PhoneApplicationPage.Resources>

This special class has a single property called Source that can be set to any object; in this sample, it’s pointing to a named control inside the pages LayoutRoot (hence the single Binding.ElementName property set)

If you look a bit down the code, you’ll find the ApplicationBarIconButton.CommandParameter where this resource is getting referenced:

<cimbalinoBehaviors:ApplicationBarIconButton
    Command="{Binding DeleteItemsCommand, Mode=OneTime}"
    CommandParameter="{Binding Source.SelectedItems, Source={StaticResource ItemsMultiselectList}}"
    IconUri="/Images/appbar.delete.rest.png"
    Text="delete" />

If we just put the two parts together, we can see that the whole objective is to bind the ApplicationBarIconButton.CommandParameter property to ItemsMultiselectList.SelectedItems property.

Obviously you’d expect to just do it directly, like this:

<cimbalinoBehaviors:ApplicationBarIconButton
    Command="{Binding DeleteItemsCommand, Mode=OneTime}"
    CommandParameter="{Binding SelectedItems, ElementName=ItemsMultiselectList}"
    IconUri="/Images/appbar.delete.rest.png"
    Text="delete" />

In reality, this approach doesn’t work from the PhoneApplicationPage point of view, due to the different XAML Namescope.

XAML Namescope??

Here is the XAML Namescope definition found in this MSDN article:

…a XAML namescope stores relationships between the XAML-defined names of objects and their instance equivalents. This is similar to the wider meaning of the term “namescope” in other programming languages and technologies.

So think of the XAML Namescope as a hash-table with each control name and it’s instance (something like IDictionary<string, FrameworkElement>).

The problem is that the page’s LayoutRoot control gets a different XAML Namescope from the page itself, so searching for a child control from inside the page just won’t work!

The following image illustrates the Namescope boundaries for a default new page:

XAML Namescope boundaries thumb

This is where the NamescopeBinding helper class makes its entry: just register an instance of this class as a page resource and bind the NamescopeBinding.Source property to the control you require outside the LayoutRoot XAML Namescope as shown in the sample code, and that’s it!

In the BindableApplicationBar sample, if you actually attach the MultiApplicationBarBehavior to the LayoutRoot instead of the page, it will work perfectly without the need for the NamescopeBinding helper class.

But my advice is to always bind the ApplicationBarBehavior and MultiApplicationBarBehavior to the page as it will provide better integration and more fluid animation, and use the NamescopeBinding helper class if needed.

I’ve created a small sample app that demonstrates the XAML Namescope behavior and how it affects your applications, which you can download from here.

Assert.ThrowsException the async way

The new Windows Phone Test Framework on Visual Studio 2012 Update 2 is a major step in the right direction for testing WP apps.

I particularly like the fact that all tests run on the emulator where they can get the full runtime environment of a real Windows Phone device.

Yet, the test framework still has some pitfalls where we realize it is just not enough!

A few weeks ago I wrote an article about one of these pitfalls, on how to run code in the UI Thread.

Now I’ve stumbled in yet another pitfall, this time on how to run the Assert.ThrowsException with async code!

Microsoft solved this issue on the Windows 8 version of the Test Framework, by adding some Task<Exception> Assert.ThrowsException(Func<Task>) methods, but there is no equivalent in Windows Phone.

This is my personal implementation of these methods for the Windows Phone Test Framework:

public static class AssertExtensions
{
    public static Task<T> ThrowsExceptionAsync<T>(Func<Task> action)
        where T : Exception
    {
        return ThrowsExceptionAsync<T>(action, string.Empty, null);
    }

    public static Task<T> ThrowsExceptionAsync<T>(Func<Task> action, string message)
        where T : Exception
    {
        return ThrowsExceptionAsync<T>(action, message, null);
    }

    public async static Task<T> ThrowsExceptionAsync<T>(Func<Task> action, string message, object[] parameters)
        where T : Exception
    {
        try
        {
            await action();
        }
        catch (Exception ex)
        {
            if (ex.GetType() == typeof(T))
            {
                return ex as T;
            }

            var objArray = new object[] { 
                "AssertExtensions.ThrowsExceptionAsync",
                string.Format(CultureInfo.CurrentCulture, FrameworkMessages.WrongExceptionThrown, message, typeof(T).Name, ex.GetType().Name, ex.Message, ex.StackTrace) 
            };

            throw new AssertFailedException(string.Format(CultureInfo.CurrentCulture, FrameworkMessages.AssertionFailed, objArray));
        }

        var objArray2 = new object[] { 
            "AssertExtensions.ThrowsExceptionAsync", 
            string.Format(CultureInfo.CurrentCulture, FrameworkMessages.NoExceptionThrown, message, typeof(T).Name)
        };

        throw new AssertFailedException(string.Format(CultureInfo.CurrentCulture, FrameworkMessages.AssertionFailed, objArray2));
    }
}

Just copy the above code to your test project and then use it like in this sample:

[TestMethod]
public async Task MyTestMethod()
{
    await AssertExtensions.ThrowsExceptionAsync<ArgumentException>(async () =>
    {
        await Windows.Storage.StorageFolder.GetFolderFromPathAsync("");
    });
}