Tag Archives: Windows Phone

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

Cimbalino Windows Phone ToolkitOne 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 MultiBindingBehavior 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!

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

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

Cimbalino Windows Phone ToolkitI 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.

The following is a small sample app that demonstrates the XAML Namescope behavior and how it affects your applications:

XAML Namescope Demo (292.52 kB)
Downloaded 547 times

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("");
    });
}

App Package Cleanup

The NuGet team released the 2.5 version yesterday, and along with a bunch of really cool new features, there was one I was particularly interested: the ability to import MSBuild targets and props files!

This means we can now have NuGet packages without any type of assembly, targeting only the project build process.

And if you’ve read this article about the issue with the current build process for Windows 8 and Windows Phone 8 apps, where the Xml Documentation gets bundled in the output packages (APPX and XAP), I have some great news: no more need to change the project file manually, as I just published a NuGet package that does those changes for you!!

All you have to do is run the following command from the Package Manager console window:

InstallPackage AppPackageCleanup

If you have NuGet Package Manager extension installed on Visual Studio, just search for AppPackageCleanup to install the Package.

Note: this package requires NuGet 2.5 as it won’t show up in the search results with previous versions of NuGet!

Windows Phone 8 Unit Testing in the UI thread with VS 2012.2 CTP4

If you’ve been following the news on the upcoming Visual Studio 2012 Update 2 (currently in CTP4), you know that we now have a fully working Unit Tests framework for Windows Phone projects!

Well, this seemed like the perfect opportunity to finally create some unit tests for the Cimbalino Windows Phone Toolkit and test this new test framework, all at once!

Works on my machineGiven that this post will require installing the VS2012.2 CTP 4, a non-final preview version software that has a “go-live” license, I think it’s only proper to apply the WOMM certification to it.

So bottom line, install it at your own risk!

So I started by installing the update, launch Visual Studio 2012, and create a new Windows Phone Unit Test App.

Then, I used NuGet to add a reference to the Cimbalino Windows Phone Toolkit and then added the following test class:

namespace Cimbalino.Phone.Toolkit.Tests.Converters
{
    [TestClass]
    public class ColorToBrushConverterTests
    {
        [TestMethod]
        public void ConvertWithColorReturnsBrush()
        {
            var converter = new ColorToBrushConverter();

            var expected = Colors.Blue;

            var actual = converter.Convert(Colors.Blue, typeof(string), null, CultureInfo.CurrentCulture);

            Assert.IsInstanceOfType(actual, typeof(SolidColorBrush));
            Assert.AreEqual(((SolidColorBrush)actual).Color, expected);
        }
    }
}

This simple class will test the ColorToBrushConverter.Convert method as to check for the proper creation of a SolicColorBrush out of a specific Color.

When I ran the test, this is what happened:

Windows Phone Unit Test results

As you can see here, we got an “Invalid cross-thread access” error message; this is the result of all tests running on a special “test app” inside the Emulator, but the really bad news is that they all run in a background thread.

Apparently, if this was a Windows Store app we could just change the [TestMethod] attribute with the proper [UITestMethod] one as to mark the requirement of running the test in the UI Thread, but unfortunately, the attribute is currently missing from the Windows Phone test framework!

So I decided to fix that and create my very own UITestMethodAttribute, and here it is:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class UITestMethodAttribute : TestMethodAttribute
{
    public override TestResult[] Execute(ITestMethod testMethod)
    {
        TestResult[] result = null;

        var ar = new AutoResetEvent(false);

        Deployment.Current.Dispatcher.BeginInvoke(() =>
        {
            try
            {
                result = base.Execute(testMethod);
            }
            finally
            {
                ar.Set();
            }
        });

        ar.WaitOne();

        return result;
    }
}

If you don’t like using the AutoResetEvent, then you can use this alternative version with the new Tasks:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class UITestMethodAttribute : TestMethodAttribute
{
    public override TestResult[] Execute(ITestMethod testMethod)
    {
        var task = ExecuteOnUi(testMethod);

        task.Wait();

        return task.Result;
    }

    private Task<TestResult[]> ExecuteOnUi(ITestMethod testMethod)
    {
        var tsc = new TaskCompletionSource<TestResult[]>();

        Deployment.Current.Dispatcher.BeginInvoke(() =>
        {
            tsc.SetResult(base.Execute(testMethod));
        });

        return tsc.Task;
    }
}

For a usage sample, please refer to the Cimbalino.Phone.Toolkit.Tests project!

Other approaches to solve this issue can be found in this post by Joost van Schaik or this gist from Jake Ginnivan, both relying on just running the necessary code in the UI instead of the full test method as with the above approach.

Cimbalino Windows Phone Toolkit: MultiApplicationBarBehavior

Cimbalino Windows Phone ToolkitMy previous article showed how to use the ApplicationBarBehavior from the Cimbalino Windows Phone Toolkit to build applications with MVVM pattern and still use the Application Bar control without the need for any code-behind.

More than just controlling the app bar from the ViewModel, the ApplicationBarBehavior adds some nice new properties that you can’t find in the native app bar control.

Such is the nature of the IsVisible property found in the buttons and menu items, allowing to change the app bar contents with some ease!

To demonstrate the IsVisible property, I’ll use the sample code from the previous article: this will generate an app bar with 3 buttons, the first two will appear when IsSelectionDisabled = true and the 3rd one will appear when IsSelectionEnabled = true (the opposite state).

This is the recorded animation of what the state changing causes to the application bar buttons visibility:

ApplicationBarBehavior

As you can see, it works perfectly! Well, almost perfectly…

If you look really closely, you’ll notice that the animation doesn’t seem quite that smooth!

By making time go a bit slower, this is what is actually happening:

ApplicationBarBehavior (Slower)

As you can see above, the buttons move before the animation starts!

This behavior is due to the nature of the ApplicationBar.Buttons and ApplicationBar.MenuItems collections: their type is IList, and as such, all we really have is the Add, Remove and Clear methods to manipulate the collection items.

And that is exactly what the ApplicationBarBehavior does behind the scenes: add or remove items when the IsVisible property of each item changes, and that is why we actually see this animation glitch.

Now presenting the MultiApplicationBarBehavior

Fixing this issue will require changing the whole application bar associated with the page, instead of just adding or removing buttons one by one.

And that is exactly what the MultiApplicationBarBehavior does: it allows you to have multiples application bar controls representing different states of the app bar!

Here’s the same app bar from the first article, now using the “multi” version:

<!-- remaining code -->

<Grid x:Name="LayoutRoot" Background="Transparent">
    <i:Interaction.Behaviors>
        <cimbalino:MultiApplicationBarBehavior SelectedIndex="{Binding ApplicationBarSelectedIndex}">
            <cimbalino:ApplicationBar>
                <cimbalino:ApplicationBarIconButton Command="{Binding AddItemCommand, Mode=OneTime}" IconUri="/Images/appbar.add.rest.png" Text="add" />
                <cimbalino:ApplicationBarIconButton Command="{Binding EnableSelectionCommand, Mode=OneTime}" IconUri="/Images/appbar.manage.rest.png" Text="select" />
            </cimbalino:ApplicationBar>
            <cimbalino:ApplicationBar>
                <cimbalino:ApplicationBarIconButton Command="{Binding DeleteItemsCommand, Mode=OneTime}" CommandParameter="{Binding SelectedItems, ElementName=ItemsMultiselectList}" IconUri="/Images/appbar.delete.rest.png" Text="delete" />
            </cimbalino:ApplicationBar>
        </cimbalino:MultiApplicationBarBehavior>
    </i:Interaction.Behaviors>

    <!-- remaining code -->

</Grid>

<!-- remaining code -->

Major difference here is the presence of multiple ApplicationBar entries, but also the MultiApplicationBarBehavior.SelectedIndex property which will allow you to select what app bar you want to show.

Here’s the recording of the app bar transition now:

MultiApplicationBarBehavior

Much nicer, but just to make sure, here is the same animation but about 5 times slower:

MultiApplicationBarBehavior (Slower)

Cimbalino Windows Phone Toolkit: ApplicationBarBehavior

Cimbalino Windows Phone ToolkitThe Windows Phone Application Bar has been a true headache for developers since day one, given that this object is not a FrameworkElement.

What this means is that we are unable to apply Styles or Templates to an ApplicationBar object, but most important, we are unable to bind to its properties, something that is a big issue when you what to use MVVM pattern in you apps.

Surely MVVM is not a closed pattern, and as such there are alternatives to overcome this issue (like this one or this one)!

In my case, in order to access the ApplicationBar in my apps in a more “MVVM’ed” way, I created the ApplicationBarBehavior that you can find in the Cimbalino Windows Phone Toolkit!

This Behavior, when applyed to a PhoneApplicationPage or it’s LayoutRoot element, allows to create and maintain a fully bindable Application Bar, and as such applying a more consistent MVVM pattern.

Here’s a small sample code for it:

<!-- remaining code -->

<Grid x:Name="LayoutRoot" Background="Transparent">
    <i:Interaction.Behaviors>
        <cimbalino:ApplicationBarBehavior>
            <cimbalino:ApplicationBarIconButton Command="{Binding AddItemCommand, Mode=OneTime}" IconUri="/Images/appbar.add.rest.png" Text="add" IsVisible="{Binding IsSelectionDisabled}" />
            <cimbalino:ApplicationBarIconButton Command="{Binding EnableSelectionCommand, Mode=OneTime}" IconUri="/Images/appbar.manage.rest.png" Text="select" IsVisible="{Binding IsSelectionDisabled}" />
            <cimbalino:ApplicationBarIconButton Command="{Binding DeleteItemsCommand, Mode=OneTime}" CommandParameter="{Binding SelectedItems, ElementName=ItemsMultiselectList}" IconUri="/Images/appbar.delete.rest.png" Text="delete" IsVisible="{Binding IsSelectionEnabled}" />
        </cimbalino:ApplicationBarBehavior>
    </i:Interaction.Behaviors>

    <!-- remaining code -->

</Grid>

<!-- remaining code -->

In this small code sample we can see the ApplicationBarBehavior and in it, some ApplicationBarIconButton (like you would do in the current one), and quickly we notice some new properties like Command, CommandParamenter, and IsVisible (something we can’t even find in the base Windows Phone ApplicationBar); obviously, even the properties Text and IconUri are bindable, allowing for easy localization! ;)