Feeds:
Posts
Comments

Archive for July, 2009

This is a serious question, though maybe you’re thinking about the wrong answers. See, I understand why one would want to decouple communication between a subject and observer. What I don’t understand is why we need a “fancy schmancy aggregator object” to do this. I’ve seen several designs, and several criticisms of every one of those designs and in every case I wonder if there’s a design that could make everyone happy. However, more importantly, I come back to wondering why we need an aggregator at all. Seems to me a static event and Publish method would eliminate the need for an aggregator at all.

public static class Events
{
    public static event EventHandler CustomerAdded;

    public static void PublishCustomerAdded(object sender)
    {
        EventHandler handler = CustomerAdded;
        if (handler != null)
        {
            handler(sender, EventArgs.Empty);
        }
    }
}

To subscribe to the “aggregated event” you just follow normal conventions.

private void Subscribe()
{
    Events.CustomerAdded += OnCustomerAdded;
}

To publish the “aggregated event” you simply call the method provided for this purpose.

private void Publish()
{
    Events.PublishCustomerAdded(this);
}

There’s lots of benefits to this design.

  • No “magic strings” are utilized.
  • We’re strongly typed.
  • There’s no runtime overhead involved in registering and looking up an “aggregated event”.
  • The code follows the same patterns as “non-aggregated events” do.
    • This means the same mechanisms can be employed for “weak events”, though it also means strong references by default.
    • This also means there’s no artificial constraints on the event signature.
  • You can control who can publish the event. The Onyx View.ViewCreated event is an example, where only instances of the View type itself can publish the event, but subscribers are still decoupled from the actual instances of the View type.

The only downside I see is that there doesn’t have to be a single “registry” for aggregated events (though there can be), but whether or not that’s a downside is certainly debatable. I’m really curious what other people see as reasons to prefer an EventAggregator over this simple pattern?

Read Full Post »

In my last blog post I referred to the Behavior as “your trusty ViewModel bazooka”. Well, if Behaviors are akin to bazookas, I guess services must be akin to something on the scale of the Death Star! Seriously, there’s no problem that can’t be solved by the use of a service. The concept is that powerful. That’s why they are the integral part of Onyx. Every problem that ever came up that I couldn’t find another solution for, services could be used to save the day.

Services?

So, what is a service? This very question got asked on Stack Overflow in response to an answer I gave to another question. Like I answered on Stack Overflow, put simply, a service is an object that provides functionality to be used by other objects. These services are generally provided to the other objects through either the Service Locator or Inversion of Control patterns. Onyx provides a generalized mechanism for this using the Service Locator pattern, hopefully with the hooks necessary to override this to use Inversion of Control instead.

In any event, services are powerful, because they are reusable pieces of code that can be easily replaced with alternative implementations. This means that at runtime they can do all the logic necessary to accomplish your task in a tightly coupled fashion, just as you would have in the old days before the ViewModel pattern using event handlers in your codebehind. Then in your tests you can replace this behavior with test doubles that provide the behavior you need for the test in a way that’s not coupled to any UI.

Message Boxes

Let’s try and make this concrete with an example. One problem that everyone new to the ViewModel design pattern asks about is how you display a MessageBox to the user in response to something that occurs in a Command handler in the ViewModel. You can’t simply call MessageBox.Show, because that’s makes the code impossible to test. This is one problem for which, although there might be alternative solutions, the best solution is to use a service.

The first thing to do when here is to define our service. Since a service needs to be replaceable, we need to use either an abstract class or an interface to define the service. We’ll stick with using an interface.

public interface IDisplayMessage
{
    void ShowMessage(string message);
}

I’ve kept this very simple for this blog post. Onyx actually defines an IDisplayMessage service that’s more complete, allowing you to fully specify all of the optional parameters that you can supply when calling MessageBox.Show, but that would be a distraction to this conversation. OK, the service is defined. Now we need to provide an implementation.

internal class DisplayMessageService : IDisplayMessage
{
    public void ShowMessage(string message)
    {
        MessageBox.Show(message);
    }
}

Again, this is a simplified implementation for the purposes of discussion here. All that our service does is delegate to MessageBox.Show, which is a tightly coupled implementation. That’s fine, because when we use the service, we won’t be tightly coupled, since we can provide a different implementation of the service. For instance, not only can we provide a test double in our unit tests, but we could also decide that instead of display a modal dialog, all such messages should be displayed in a list in a docked message window in our UI, and this change doesn’t require any modification to the ViewModels that use the service.

Next up, we have to supply the service to our ViewModel somehow. We’ll do this by adding a parameter to the constructor, which is the Inversion of Control pattern.

public Window1ViewModel(IDisplayMessage displayMessage)
{
    this.displayMessage = displayMessage;

Then in the ViewModel we can use this service to display a message.

this.displayMessage.ShowMessage(string.Join(Environment.NewLine, this.SelectedDisciples.ToArray()));

Keeping things simple, we’ll just manually supply the service when we create the ViewModel (this is often referred to as “poor man’s dependency injection” since we’re not using a container).

this.DataContext = new Window1ViewModel(new DisplayMessageService());

Keep in mind that everything we did here was the simplest possible implementation that can illustrate how to use services, and not necessarily the best or most maintainable way of doing this. I don’t want to confuse you with the extra code necessary to use a container for either service location or dependency injection, as those are architectural artifacts not necessary to the concept of using services.

So, we declared a service for displaying messages to the user, implemented a version that will display a MessageBox, provided the service to the ViewModel, and used it to display a message. We now have a ViewModel that displays a message in a way that’s decoupled from how the message is displayed and thus decoupled from the View and testable. All of this easily allowed us to solve a problem that at first look appears to be extremely difficult to implement when following the ViewModel design pattern. You’ll find nearly everything you run into that appears to be complicated to do when following the ViewModel pattern is actually easy to solve by using a service. In fact, you can find yourself going overboard here, and use services for problems that are better solved using other mechanisms. For instance, you could use a service to replace data bindings, but that wouldn’t be the correct solution to the problem. Don’t be too enticed by the power of services. Look first for alternative solutions, and if none present themselves, then look to the service as your solution. Remember the analogy from the last post, which is even more poignant this time around. You wouldn’t go duck hunting with a death star, nor should you solve most day to day problems with services. However, it’s nice to know there’s no problem you can’t solve as long as you’ve got services to back you up.

Read Full Post »

I’ve said online in a few different places that attached behaviors and services are your “big guns” when developing WPF applications that follow the ViewModel design pattern. If you run into something you’re finding difficult to program due to the nature of the ViewModel pattern, these are the concepts that will help get you out of the corner you’ve been painted into. I thought I’d write a little series of blog entries that elaborate on this.

The “Little Guns”

First, I’d better step back. I call the attached behavior and services “big guns” for a reason. They should not be your tool of choice on a daily basis. You wouldn’t go duck hunting with a bazooka, nor should you solve most day to day problems with behaviors or services. Most of the day to day problems are solved with the “little guns”, data bindings and commands. We’re only going to pull out the “big guns” when the problem is so large that the “little guns” wouldn’t put a dent in it.

Attached Properties

OK, today we’re just going to discuss attached behaviors. But in order to do so, we need to back up a little bit and discuss attached properties. I suppose, if I were really going to be thorough, I should back all the way up and discuss dependencies properties, but if you’re new enough to WPF to need me to go back that far, you’re not ready for this discussion ;).

An attached property is a dependency property that’s defined on one type, but that can be applied to a dependency object of another type. The typical example given when talking about attached properties are the Grid.Row and Grid.Column properties. These are defined by, and used by, the Grid type, but you set their values on children of the Grid that probably are different types that are entirely unaware of the Grid type and these properties.

    <Grid Margin="4">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <ListBox Grid.Row="0"/>
        <Button Grid.Row="1" Content="Test"/>
    </Grid>

The Remora Pattern

Early in the WPF lifetime, one BenCon blogged about a pattern that he called the Ramora (sic) pattern. I’m not sure if he’s the first to discover this pattern or not, but I’m going to give him credit, as folks are want to do on the intarweb thingy. Over time, this pattern came to be more commonly known as an “attached behavior”, and more recently with the Blend SDK we now just call it a Behavior (though a Behavior is a class that encapsulates this stuff, so don’t let that confuse you). Basically, and attached behavior is just an attached property that when set it applies some behavior to the item it’s attached to, usually by subscribing to some event on the item. If that’s clear as mud to you, hopefully things will become more clear as we actually implement a behavior.

This idea is important to the ViewModel design pattern because often what you’re wanting to do is enable the ViewModel to change the behavior of the View in some way.

Selection

We’re going to look at one of the more common problems you may face when following the ViewModel pattern that’s easily solved by using an attached behavior: tracking and changing the selection in a multi-select ListBox. For single-selection you have a couple of options. The CollectionView has a CurrentItem property that will be the selected item. However, it doesn’t expose a property that represents the selected items. On the ListBox itself the SelectedItem is a dependency property that you can bind to a property on your ViewModel. However, the SelectedItems is a read-only dependency property and can’t be used to track selection directly. The ListBox does have a SelectionChanged event that could be bound to the ViewModel, but that will only provide you with half a solution. You’re ViewModel could use this to track the selection made by the user, but could not use it to programmatically change the selection.

An attached behavior is a perfect solution to this problem. An attached property can be used to bind to a collection exposed by the ViewModel, and the remora pattern can then be used to monitor changes to either the ViewModel’s collection or the ListBox.SelectedItems collection, and apply those changes to the other collection.

public static class Selection
{
    private static readonly DependencyProperty SynchronizerProperty =
        DependencyProperty.RegisterAttached(
            "Synchronizer",
            typeof(ListSynchronizer),
            typeof(Selection));

    public static readonly DependencyProperty ItemsProperty =
        DependencyProperty.RegisterAttached(
            "Items",
            typeof(IList),
            typeof(Selection),
            new PropertyMetadata(null, OnItemsChanged));

    public static IList GetItems(DependencyObject source)
    {
        return (IList)source.GetValue(ItemsProperty);
    }

    public static void SetItems(DependencyObject source, IList value)
    {
        source.SetValue(ItemsProperty, value);
    }

    private static void OnItemsChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
    {
        IList targetList = null;

        MultiSelector selector = source as MultiSelector;
        if (selector != null)
        {
            targetList = selector.SelectedItems;
        }
        else
        {
            ListBox listBox = source as ListBox;
            if (listBox != null)
            {
                targetList = listBox.SelectedItems;
            }
        }

        if (targetList == null)
        {
            return;
        }

        ListSynchronizer synchronizer = (ListSynchronizer)source.GetValue(SynchronizerProperty);
        if (synchronizer != null)
        {
            synchronizer.Dispose();
        }

        IList sourceList = (IList)e.NewValue;
        if (sourceList == null)
        {
            return;
        }

        synchronizer = new ListSynchronizer(sourceList, targetList);
    }
}

Internally here we’re using a ListSynchronizer type to encapsulate all of the event handling logic, and we’re storing an instance of this type in a private attached dependency property. Here’s the ListSynchronizer in all of its glory.

internal sealed class ListSynchronizer : IDisposable
{
    private bool disposed;
    private IList source;
    private IList target;

    public ListSynchronizer(IList source, IList target)
    {
        this.source = source;
        this.target = target;
        StartListening(this.source);
        StartListening(this.target);
        Synchronize();
    }

    ~ListSynchronizer()
    {
        Dispose(false);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private void StartListening(IList list)
    {
        INotifyCollectionChanged incc = list as INotifyCollectionChanged;
        if (incc != null)
        {
            incc.CollectionChanged += OnCollectionChanged;
        }
    }

    private void StopListening(IList list)
    {
        INotifyCollectionChanged incc = list as INotifyCollectionChanged;
        if (incc != null)
        {
            incc.CollectionChanged -= OnCollectionChanged;
        }
    }

    private void Synchronize()
    {
        Synchronize(this.target, this.source);
        if (!this.target.Cast<object>().SequenceEqual(this.source.Cast<object>()))
        {
            Synchronize(this.source, this.target);
        }
    }

    private void Synchronize(IList source, IList target)
    {
        StopListening(target);
        try
        {
            foreach (object item in source)
            {
                target.Add(item);
            }
        }
        finally
        {
            StartListening(target);
        }
    }

    private void OnCollectionChanged(
        object sender,
        NotifyCollectionChangedEventArgs e)
    {
        IList targetList = object.ReferenceEquals(sender, this.source) ? this.target : this.source;
        switch (e.Action)
        {
            case NotifyCollectionChangedAction.Add:
                PerformActionOnList(targetList, e, Add);
                break;

            case NotifyCollectionChangedAction.Move:
                PerformActionOnList(targetList, e, MoveOrReplace);
                break;

            case NotifyCollectionChangedAction.Remove:
                PerformActionOnList(targetList, e, Remove);
                break;

            case NotifyCollectionChangedAction.Replace:
                PerformActionOnList(targetList, e, MoveOrReplace);
                break;

            case NotifyCollectionChangedAction.Reset:
                Synchronize();
                break;
        }
    }

    private void PerformActionOnList(
        IList list,
        NotifyCollectionChangedEventArgs e,
        Action<IList, NotifyCollectionChangedEventArgs> action)
    {
        StopListening(list);
        try
        {
            action(list, e);
        }
        finally
        {
            StartListening(list);
        }
    }

    private void Add(IList list, NotifyCollectionChangedEventArgs e)
    {
        int itemCount = e.NewItems.Count;
        for (int i = 0; i < itemCount; i++)
        {
            int insertionPoint = e.NewStartingIndex + i;
            if (insertionPoint > list.Count)
            {
                list.Add(e.NewItems[i]);
            }
            else
            {
                list.Insert(insertionPoint, e.NewItems[i]);
            }
        }
    }

    private void MoveOrReplace(IList list, NotifyCollectionChangedEventArgs e)
    {
        Remove(list, e);
        Add(list, e);
    }

    private void Remove(IList list, NotifyCollectionChangedEventArgs e)
    {
        int itemCount = e.OldItems.Count;
        for (int i = 0; i < itemCount; i++)
        {
            list.RemoveAt(e.OldStartingIndex);
        }
    }

    private void Dispose(bool disposing)
    {
        if (this.disposed)
        {
            return;
        }

        if (disposing)
        {
            StopListening(this.source);
            StopListening(this.target);
        }

        this.disposed = true;
    }
}

OK, that code is admittedly a tad complicated, but using it is not.

        <ListBox Grid.Row="0"
                 SelectionMode="Extended"
                 ItemsSource="{Binding Disciples}"
                 ui:Selection.Items="{Binding SelectedDisciples}"/>

I should note, similar behaviors have been posted before, including one by fellow Disciple Marlon Gretch. I chose to use this one anyway, because it does the best job of illustrating how a behavior can solve a common ViewModel problem. Besides, I think I was the first person to post such a solution to this problem, though finding it is difficult. I won’t point you there now, because this is a much better implementation and description.

I hope this helps someone new to WPF and the ViewModel pattern. Next up, services!

Edit: Ran across a blog post today by Edward Tanguay with another example, binding to a PasswordBox, where behaviors allow you to work around what would otherwise be a tricky area in the ViewModel pattern (I’ll note that another Disciple Peter O’Hanlon also blogged about a behavior for this, and I’ve had this one in my bag of tricks for quite a while).

Read Full Post »

SketchFlow Book

Unless you’ve been living under a rock, or you’re not a WPF/Silverlight developer I suppose, then you’ve heard about SketchFlow. We recently were given access to this exciting new tech in a recent Blend 3 release candidate (you’ll probably want the Silverlight 3 tools and developer runtime as well).

SketchFlow allows a designer to create prototypes that use actual WPF code that will be your starting point for the real application, but using a style that makes the PHB not assume the code is close to being ready to ship. This prototype also allows the PHB and other interested parties to annotate the live running application with feedback notes and “penciled” markings. This feedback can be exported and sent back to the designer, who can quickly make suggested changes. This is probably one of the most obvious, yet never implemented (to my knowledge) ideas to ever come down the pike. It’s sheer genius!

So, we get our first access to SketchFlow last week, and now there’s already public information about a book on the subject, including a free chapter download! Haven’t read this yet, but you know I’m going to.

Read Full Post »

Value Converters

I need to get into blogging more. So, today, I’m going to start by blogging about a topic that came up in my development efforts recently. I’m going to discuss ValueConverters and an interesting way to implement them in WPF.

In case you don’t know what a ValueConverter is, it’s a class that implements the IValueConverter interface and is used to convert to and from one value to another. Often these values are of different types, but that’s not a requirement of a ValueConverter.  WPF ships with a few ValueConverters out of the box, such as the BooleanToVisibilityConverter, but there’s plenty of room for your own ValueConverters.

Josh Smith recently started a discussion on the WPF Disciples list about whether or not ValueConverters were still needed when using the ViewModel pattern. Like most such philosophical questions, I’m not sure we came to a definitive answer, but I’m going to state my opinion here. While it’s true that you could put all of your value conversions into the ViewModel, with expose properties for exactly what you want to use in the View, there are reasons to not always want to do this. First, it’s not very DRY (Don’t Repeat Yourself) to hand code the conversions over and over again in your ViewModels. ValueConverters are little pieces of code that can be reused over and over again. Second, doing all of your conversions in the ViewModel can result in more complex interfaces. For example, imagine we have some boolean value in our Model layer that will be used to determine whether or not some controls are enabled in the UI.  If it’s true, some controls will be enabled while others will be disabled. If we were to handle this entirely within the ViewModel, we’d require at least two properties, one for enabling some of the controls and another for disabling the rest. You can see how your complicating the ViewModel here when you expose two properties for the same logical state just to allow for different UI state. In a little bit I’ll show you a NotConverter that would allow you to continue to expose a single property here, which makes for a more logical interface design on the ViewModel. Finally, it usually doesn’t make sense to expose purely visual information from your ViewModel. For example, imagine that same boolean value from the Model is going to be used to change the color of some text in the UI. At first the designer decides it should be Red when the value is True, but later decides it would make the text look too much like an error indication so he wants to make it Orange instead. If you’d done the conversion in the ViewModel, you’d have to change code every time such decisions were made, while if a configurable ValueConverter had been used, the designer could just change the XAML.

So, now that I’ve explained what ValueConverters are for, and why you should still be inclined to use them despite the fact that you’re using the ViewModel pattern (you are, aren’t you?), lets dig into a little trick you can use when writing a ValueConverter. I talked earlier about a NotConverter, so let’s start with that. Imagine we’ve already coded the NotConverter in the typical fashion. Here’s how you would use the converter in your XAML.

<Window x:Class="WPFConverters.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ui="clr-namespace:WPFConverters"
    Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <ResourceDictionary>
            <ui:NotConverter x:Key="NotConverter"/>
        </ResourceDictionary>
    </Window.Resources>
    <StackPanel>
        <CheckBox IsChecked="{Binding IsDisabled}" Content="Disable"/>
        <Button Content="Test" IsEnabled="{Binding IsDisabled, Converter={StaticResource NotConverter}}"/>
    </StackPanel>
</Window>

 

You have to declare the NotConverter in a ResourceDictionary and specify the binding should use it by using the StaticResource MarkupExtension. Well, recently I stumbled upon a trick that can simplify this. The idea is to make the NotConverter not only an IValueConverter, but also a MarkupExtension itself. Doing so simplifies the XAML into this.

<Window x:Class="WPFConverters.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ui="clr-namespace:WPFConverters"
    Title="Window1" Height="300" Width="300">
    <StackPanel>
        <CheckBox IsChecked="{Binding IsDisabled}" Content="Disable"/>
        <Button Content="Test" IsEnabled="{Binding IsDisabled, Converter={ui:NotConverter}}"/>
    </StackPanel>
</Window>

 

I knew this couldn’t be a new idea, so I Googled it and came across this CodeProject article. There were several criticisms in the comments for the article about how the sample converter wasn’t really a singleton. There was also a link to a posting on this same topic by Dr. WPF. Having just read the CodeProject article, I left a comment about how this wasn’t a singleton and some perceived problems about it not being one. Shame on me. I made a classic mistake. People assume, because of the name, that a Singleton should enforce the creation of only a single instance. This isn’t true. If you read the classic GoF book on this pattern, although a single instance is typical scenario the pattern is really just about controlling how many instances are created. So, it might actually be argued that this is a Singleton. More importantly, it’s possible to implement this idea in a way that there’s no memory or performance reason to prefer the classic implementation to the MarkupExtension version, and that’s what I want to illustrate here. So, here’s the implementation of that NotConverter.

[MarkupExtensionReturnType(typeof(NotConverter))]
[ValueConversion(typeof(bool), typeof(bool))]
public class NotConverter : MarkupExtension, IValueConverter
{
    private static WeakReference Cache = new WeakReference(null);

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        NotConverter converter = (NotConverter)Cache.Target;
        if (converter == null)
        {
            converter = this;
            Cache.Target = converter;
        }

        return converter;
    }

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return !(bool)value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return !(bool)value;
    }
}

 

The trick is to use a WeakReference to cache the converter, so we won’t keep any instances of the converter alive any longer than we would with the classic implementation.  Next, the ProvideValue method will either return the cached converter, or will cache and return itself if there is no cached version. This eliminates the extra allocation pointed out in the implementations used in both the CodeProject article and the posting by Dr. WPF. Finally, the concern about the overhead of using this as a MarkupExtension is a red herring, since the classic implementation is already using a MarkupExtension (the StaticResource extension) itself. The end result, this new NotConverter should have all of the same runtime characteristics as the classic implementation, only it will be easier to use.

There’s a variation on this I want to talk about. Some ValueConverters are configurable. For instance, I want to talk about the BooleanToVisibilityConverter. The one provided by WPF isn’t configurable, and that’s a shame. I never remember if the “not visible” value is Visibility.Hidden or Visibility.Collapsed, but it doesn’t matter, you want both in different circumstances. So, I’d like to provide a BooleanToVisibilityConverter that can be configured for either behavior. But since it’s configurable, how do I use this MarkupExtension trick? By caching values for any different configuration requested!

[MarkupExtensionReturnType(typeof(BooleanToVisibilityConverter))]
[ValueConversion(typeof(bool), typeof(Visibility))]
public class BooleanToVisibilityConverter : MarkupExtension, IValueConverter
{
    private static WeakReference[] Cache = new WeakReference[] { new WeakReference(null), new WeakReference(null) };

    private Visibility negativeVisibility = Visibility.Collapsed;

    public Visibility NegativeVisibility
    {
        get { return this.negativeVisibility; }
        set
        {
            if (value == Visibility.Visible)
                throw new ArgumentOutOfRangeException("Visible is not a valid negative visibility value.");
            this.negativeVisibility = value;
        }
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        int index = NegativeVisibility == Visibility.Collapsed ? 0 : 1;
        BooleanToVisibilityConverter converter = (BooleanToVisibilityConverter)Cache[index].Target;
        if (converter == null)
        {
            converter = this;
            Cache[index].Target = converter;
        }

        return converter;
    }

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return (bool)value ? Visibility.Visible : NegativeVisibility;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return (Visibility)value == Visibility.Visible ? true : false;
    }
}

 

Our cache is now an array, and we store each of the differently configured converters requested by the MarkupExtension using the same technique as we did with our NotConverter.

Hope these ideas are useful for somebody.

Read Full Post »