Dude, where's my Kaizen?

Notifications the WPF Way (I Guess), Part II

Back again to my take on the Notification pattern with WPF. Last time I talked briefly about my motivation for this little series. This time we dive more into the nuts and bolts of my example implementation.

How the ViewModel notifies the UI

I defined an interface called INotificationSource for this. This interface defines only I member which exposes a NotificationCollection. NotificationCollection is just a standard ObservableCollection<Notification> with some additional bits in it (such as retrieving a collection of Notifications for a given source). By deriving from ObservableCollection you get the CollectionChangedEvent on the collection for free.

The interface that needs to be implemented by a ViewModel
1
2
3
4
public interface INotificationSource
{
    NotificationCollection Notifications {get;}
}

In my current app I’ve got a Layer Supertype for ViewModels which implements this interface.

Glue code for transferring Notifications from the ViewModel into the logical tree

As I mentioned in the last post I’m using the Attached Behavior Pattern for transferring Notifications from the ViewModel to the related elements in the logical tree (When I say related I’m referring to the FrameworkElements bound to my ViewModel via DataBinding). The class responsible for the transfer is a DependencyObject derived class, called ValidationBehavior. This class defines two attached DependencyProperties, IsEnabled and Notifications.

Our attached validation behavior
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
 public class ValidationBehavior : DependencyObject
 {
     public static readonly DependencyProperty IsEnabledProperty;
     public static readonly DependencyProperty NotificationsProperty;

     static ValidationBehavior()
     {
         IsEnabledProperty =  DependencyProperty.RegisterAttached(
                                 "IsEnabled",
                                 typeof(bool),
                                 typeof(ValidationBehavior),
                                 new FrameworkPropertyMetadata(OnValidationBehaviorEnabled));

         NotificationsProperty = DependencyProperty.RegisterAttached(
                                 "Notifications",
                                 typeof(NotificationCollection),
                                 typeof(ValidationBehavior),
                                 new PropertyMetadata(null));
     }

     public static bool GetIsEnabled(DependencyObject host)
     {
         return (bool) host.GetValue(IsEnabledProperty);
     }

     public static void SetIsEnabled(DependencyObject host, bool isEnabled)
     {
         host.SetValue(IsEnabledProperty, isEnabled);
     }

     public static NotificationCollection GetNotifications(DependencyObject host)
     {
         return (NotificationCollection)host.GetValue(NotificationsProperty);
     }

     public static void SetNotifications(DependencyObject host, NotificationCollection notification)
     {
         host.SetValue(NotificationsProperty, notification);
     }
}

The attached DependencyProperty IsEnabled is used to attach our behavior to the target element marked with the property. Notice the OnValidationBehaviorEnabled handler which is called when the value of the registered attached DependencyProperty has changed. The attached DependencyProperty Notifications will later hold the collection of Notifications extracted from the ViewModel by our attached behavior. By having the NotificationCollection as an attached property you’re able to bind against it from XAML (as we’ll see in the following post). If you recall the last post about this topic, maybe you remember that I didn’t actually set the attached property IsEnabled in the ViewModels XAML file. You could configure the behavior in the related XAML file but I didn’t want to do this for all my ViewModels. Because of this I decided to use Styles for this.

XAML styles to wire it up
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!-- The global application class -->
<Application x:Class="Notifications.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Application.Resources>
        <ResourceDictionary Source="Resources/Theme.xaml" />
    </Application.Resources>
</Application>

<!-- My XAML file containing the resources -->
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Fx="clr-namespace:Notifications.Fx">

    <Style TargetType="Control">
        <Setter Property="Fx:ValidationBehavior.IsEnabled" Value="true" />
    </Style>

    <Style TargetType="TextBox" BasedOn="{StaticResource {x:Type Control}}" />

</ResourceDictionary>

When the Style is applied the IsEnabled attached property will be automatically set on all elements based on that style and this brings us into the position to hook into the elements events and access the elements data. The OnValidationBehaviorEnabled handler is actually straight forward.

Attach to the target FrameworkElement
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
private static void OnValidationBehaviorEnabled(
    DependencyObject dependencyObject,
    DependencyPropertyChangedEventArgs args)
{
    var frameworkElement = (FrameworkElement)dependencyObject;

    // Get the DataContext from the element. Mostly this DataContext is not directly
    // set on the element but rather derived from the parents DataContext
    var notificationSource = frameworkElement.DataContext as INotificationSource;

    if (notificationSource == null)
    {
        return;
    }

    // Clear related Notifications of an element when the element
    // got the focus.
    frameworkElement.GotFocus += ClearNotificationOnFocus;

    // Hook into the CollectionChanged event of the NotificationCollection.
    // I'm using a closure here in order to capture the FrameworkElement.
    notificationSource.Notifications.CollectionChanged += (sender, collectionChangedArgs) =>
    {
        var notifications = GetNotifications(notificationSource, frameworkElement);

        SetNotification(
            frameworkElement,
            notifications);
    };
}

The anonymous event handler registered for the CollectionChangedEvent tries to get the collection of Notifications for the FrameworkElement.

Extracting the notifications for a particular element
1
2
3
4
private static NotificationCollection GetNotifications(INotificationSource notificationSource, FrameworkElement frameworkElement)
{
    return notificationSource.Notifications.AllNotificationsFor(frameworkElement.Name);
}

As you can see this particular piece of code has a little quirk right now. It relies on the convention / assumption that the property on the ViewModel and the bound FrameworkElement share the same name. It was the easiest thing to do. It would also be easy to introduce another attached property for this in order to specify the name of the related ViewModel property. However this wouldn’t be 100% DRY because you’re most likely going to specify the property via the Binding MarkupExtension, too. I’m open to suggestions of how this correlation can be done better. The last missing code piece is the handler which clears the Notification when it gets focus. It simply sets the attached Notification property to null.

Resetting a notification on focus
1
2
3
4
5
private static void ClearNotificationOnFocus(object sender, RoutedEventArgs e)
{
    var elementWithNotification = (FrameworkElement)e.OriginalSource;
    elementWithNotification.SetValue(NotificationProperty, null);
}

Closing thoughts

I hope you’re getting a feeling for what I wanted to show with this little post series. Today I talked mostly about how Notifications can be transfered from the ViewModel into the WPF tree. While the code currently has some pieces in it that imho should be refactored (correlation of the Notifications, CollectionChangedEvent currently reloads all Notifications), I hope you saw in this post that it’s relatively easy to add such an ability to your app infrastructure without a) having a base class constraint b) a lot of imperative code and c) doing a lot of configuration. The next post will conclude this little series mostly with XAML stuff. We’re going to cover how to combine the different tools (DataTrigger, DataTemplates, ControlTemplates, Converter) that WPF offers in order to fire up a Tooltip containing all Notifications for an element.

CU next time …

Notifications the WPF Way (I Guess), Part I

Update 2.11.2009: I removed the DependencyObject and DependencyProperty references from the ViewModel. The solution works fine without them.

This is the start of a small mini series about how I would currently approach the Notification Pattern in a WPF application, using the default WPF practices and patterns. Think about it as a step by step guide for using DataBinding, Control-Templates, Styles, Resource-Inheritance, Converters and the Attached-Behavior-Pattern for displaying Notifications in the WPF-UI. (I guess most of this is also doable in Silverlight too, but I’ve never done anything with SL so I can’t say for sure). I’ve also prepared a little bit of sample code for this topic which will be downloadable soon.

First, some cautious warnings

I’m by no means a WPF-expert. I’m still in the learning phase. So, if there are more obvious or intuitive solutions to the problem, or I’m plain wrong about this, feel free to comment. I’m sure there is A LOT room for improvement.

What I’ve left out intentionally

I tried to strip everything unnecessary for the scope of the post from the code. This includes for instance IoC, Convention over Configuration, Code-Contracts, Expression-based Databinding setup and some base class or extension refactorings. Don’t get me wrong, I absolutely value those elements, but I wanted the example to be as easy as possible while being somewhat useful for a ‘real world’ application. The code might look a bit raw at at some edges because of this. So please keep that in mind before throwing with stones ;-)

Some other prerequesites

A while back I wrote a post about implementing the Notification-pattern using System.Componentmodel.DataAnnotations. It demonstrates the implementation of a generic validator based on the DataAnnotation attributes. Besides that, this post about the Attached-Behavior-Pattern will also be useful for this mini-series. Please give them a short visit if you haven’t read them yet.

The example scenario

The scenario I’m going to use for the example is a very simple sign up form. It contains two input fields for username / email and a ‘sign-up’ button. It looks like this.

image

Rules associated with the fields are:

  1. Username is required and must at least be 5 characters long.
  2. Email is required and must contain a valid email address.

If any of the rules is broken, the related element should be visually highlighted …

image

… and when you hover over the element you’ll get a detailed description of the error from a tooltip.

image

I’m using the PresentationModel / MVVM pattern for the UI since it seems to be the default UI pattern in WPF.

This is how I would like my SignUpView to be
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<Window x:Class="Notifications.SignUpView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <GroupBox
            Grid.Column="1"
            Grid.Row="1"
            Header="Sign up"
            BorderThickness="2"
            VerticalAlignment="Center"
            HorizontalAlignment="Center"
            MaxWidth="300"
            MaxHeight="600">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <Label
                    Content="Username:"
                    VerticalAlignment="Bottom"
                    Margin="10,0,10,0"
                    Grid.Row="0"
                    Grid.Column="0" />
                <Label
                    Content="Email:"
                    VerticalAlignment="Bottom"
                    Margin="0,0,10,0"
                    Grid.Row="0"
                    Grid.Column="1" />
                <TextBox
                    Name="Username"
                    MinWidth="100"
                    MaxHeight="30"
                    Margin="10,0,10,10"
                    Grid.Row="1"
                    Grid.Column="0"
                    TabIndex="0"
                    Text="{Binding Path=Username, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}" />
                <TextBox
                    Name="Email"
                    MinWidth="100"
                    MaxHeight="30"
                    Margin="0,0,10,10"
                    Grid.Row="1"
                    Grid.Column="1"
                    Text="{Binding Path=Email, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}"
                    TabIndex="1" />
                <Button
                    MaxHeight="30"
                    Grid.Row="1"
                    Margin="0,0,10,10"
                    Grid.Column="2"
                    Content="Sign up!"
                    TabIndex="3"
                    Command="{Binding Path=SignUpCommand, Mode=OneWay}" />
            </Grid>
        </GroupBox>
    </Grid>
</Window>
This is how I would like my SignUpViewModel to be
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
public class SignUpViewModel : INotificationSource
{
    private readonly NotificationCollection _notifications;
    private readonly DelegateCommand _signUpCommand;
    private readonly ISignUpService _signUpService;
    private readonly IValidator<SignUpViewModel> _validator;

    #region Constructors

    public SignUpViewModel(IValidator<SignUpViewModel> validator, ISignUpService signUpService)
    {
        _validator = validator;
        _signUpService = signUpService;
        _notifications = new NotificationCollection();
        _signUpCommand = new DelegateCommand(TrySignUp);
    }

    #endregion

    #region Properties

    [Required(ErrorMessage = "Field 'Username' is missing")]
    [MinimumStringLength(5)]
    public string Username
    {
        get;
        set;
    }

    [Required(ErrorMessage = "Field 'Email' is missing")]
    [MinimumStringLength(5)]
    public string Email
    {
        get;
        set;
    }

    public ICommand SignUpCommand
    {
        get { return _signUpCommand; }
    }

    public NotificationCollection Notifications
    {
        get { return _notifications; }
    }

    #endregion

    #region Private methods

    private void TrySignUp()
    {
        if (!IsValid())
        {
            return;
        }

        _signUpService.TrySignUp(Username, Email);
    }

    private bool IsValid()
    {
        Notifications.Clear();

        _validator.Validate(this, Notifications);

        return Notifications.ContainsErrors;
    }

    #endregion
}

Did you notice it?

There is NO CODE in the View (Xaml and code behind) or the ViewModel which displays the Notifications.There’s also no base class for View or ViewModel where the code might be. What’s there on the other hand is only a collection of Notifications hanging of the ViewModel which is filled by the Validator. You might yourself now ask: Where is the damn glue code? Yeah I know dumb question because I answered it mostly in the introduction of the post. The interesting thing is that it isn’t a single location. As you will see the responsibilities for achieving the effect are separated between several components.

In the next posts we’re going to take a look at

  • how to use the Attached-Behavior-Pattern together with Styles and resource based inheritance in order to match the Notification (s) from the ViewModel to the related FrameworkElements in the logical WPF tree.
  • how to use a DataTrigger on an Attached Property in order to setup the Tooltip and showing the red border.
  • how to bind the Tooltip correctly to the related Notification(s).

I hope I made you at least a bit curious …

xUnit.BDDExtensions Now Runs With xUnit 1.5 Final

I’ve just upgraded the trunk to the final 1.5 version of xUnit released last week. This update now allows BDDExtensions to be used with the latest version independant resharper runner for xUnit from xunitcontrib.

Current Version is 1.0.1.16. You can download it here or get the latest sources from the trunk.

Happy specifying …

Diving Into the StoryTeller Trunk, Part 9: ScreenSubject & ScreenFactory

Hello back again on my little exploration of the UserInterface implementation of Jeremy Millers StoryTeller. I’d like to start today with a little excuse (oh my). Although I said last time that the current post would be focused on the ScreenConductor, I decided to delay that at least for one post in the series in order to add some content related to what Jeremy calls ScreenSubject and ScreenFactory. I consider them to be fairly simple but yet really powerful pattern which can help you a lot to structure your UI layer, especially the fine line of the UI layer where the UI infrastructure meets the common application code. It’s also a very good example of applying the Open Closed Principle.

The common use case for the ScreenSubject

Lets first start with a little description of the usage of the two patterns in StoryTeller. When application code wants to open a new screen in StoryTeller it’ll probably use one of the OpenScreen overloads on the IScreenConductor facade in order to do that.

Part of the IScreenConductor interface
1
2
3
4
5
public interface IScreenConductor
{
  void OpenScreen(IScreenSubject subject);
  void OpenScreen() where T: IScreenSubject;
}

The common use case for the ScreenSubject can be easily depicted using a tool we all know quite well, Visual Studio. Think about it: What happens when you click onto a source code file in the Source Code Explorer for the first time? Well, a new tab is created displaying the content of the file. However, if you click the item in the Source Control Explorer the second time, the previously created tab gets activated and NO NEW TAB IS CREATED.

How is this implemented

Let’s take a look at how this behavior is implemented in StoryTeller. The following code snippet shows a very small part of the ScreenConductor. I’ve inline some comments in order to make it more visible what is going on there.

The OpenScreen method
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public virtual void OpenScreen(IScreenSubject subject)
{
  //_screens is of type IScreenCollection 
  if (subject.Matches(_screens.Active))
  {
    return;
  }

  //This simply makes a LINQ-lookup on the ScreenCollection 
  //using ScreenSubject.Matches as a predicate 
  IScreen screen = findScreenMatchingSubject(subject);

  if (screen == null)
  {
    //This passes the global IScreenFactory into the 
    //ScreenSubjects CreateScreen method in order to create 
    //the screen. 
    screen = createNewActiveScreen(subject);
  }
  else
  {
    activate(screen);
  }

  _screens.Show(screen);
}

The IScreenSubject abstraction plays a quite important role in this use case. The interface defines only two methods matching the responsibilities of the ScreenSubject

The IScreenSubject interface
1
2
3
4
5
public interface IScreenSubject
{
  bool Matches(IScreen screen);
  IScreen CreateScreen(IScreenFactory factory);
}

As we saw in the ScreenConductor snippet the Matches method is used as a predicate in order to find the related screen. The CreateScreen method isn’t directly shown in the snippet, but it’s not that complicated. It’s responsible for coordinating the creation of a screen. When I say coordination I’m referring to the fact that the actual screen creation is the responsibility of the IScreenFactory (which is just a simple wrapper around StructureMap).

The IScreenFactory interface
1
2
3
4
5
public interface IScreenFactory
{
  T Build<T>() where T : IScreen;
  IScreen<T> Build<T>(T subject);
}

With this design in place we have a very nice extension point in place to do all kinds of things around the screen creation. Want to do some deferred data loading before the screen is shown? That’s your place. Maybe you want to show some progress indicator while doing this. Guess what, that’s your place to do this. And the best of it: The screen doesn’t have to know anything of this, you can free him of this kind of logic. There’re some base classes which provide some base implementation for different use cases in StoryTeller. I’m only going to show one of them, the ScreenSubject<T>. This class adds a bit generics on top of the ScreenSubject (in order to allow auto-registration using StructureMaps convention over configuration features).

ScreenSubject
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// Marker interface 
public interface IScreenSubject<T> : IScreenSubject { }

public class ScreenSubject<T> : IScreenSubject<T>
{
  private readonly T _subject;

  public ScreenSubject(T subject)
  {
    _subject = subject;
  }

  #region IScreenSubject Members 

  public bool Matches(IScreen screen)
  {
    var specific = screen as IScreen;

    if (specific == null)
      return false;

    return specific.Subject.Equals(_subject);
  }

  public IScreen CreateScreen(IScreenFactory factory)
  {
    return factory.Build(_subject);
  }

  #endregion 

  public bool Equals(ScreenSubject<T> other)
  {
    if (ReferenceEquals(null, other))
      return false;

    if (ReferenceEquals(this, other))
      return true;

    return Equals(other._subject, _subject);
  }

  public override bool Equals(object obj)
  {
    if (ReferenceEquals(null, obj))
      return false;

    if (ReferenceEquals(this, obj))
      return true;

    if (obj.GetType() != typeof (ScreenSubject<T>))
      return false;

    return Equals((ScreenSubject<T>) obj);
  }

  public override int GetHashCode()
  {
    return _subject.GetHashCode();
  }
}

The basic idea used in this implementation of IScreenSubject is that a ScreenSubject is related to a single data instance. Coming back to the Visual Studio example, this could have been represented as something like ScreenSubject<SourceCodeFile>. Really interesting …

The last code snippet for today I’d like to show is how the ScreenFactory is actually implemented. As usual really short, not very much code.

The ScreenFactory
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class ScreenFactory : IScreenFactory
{
  private readonly IContainer _container;

  public ScreenFactory(IContainer container)
  {
    _container = container;
  }

  #region IScreenFactory Members

  public SCREEN Build<SCREEN>() where SCREEN : IScreen
  {
    return _container.GetInstance<SCREEN>();
  }

  public IScreen<T> Build(T subject)
  {
    return _container.With(subject).GetInstance<T>();
  }

  #endregion 
}

I really like the way how StructureMap allows injecting transient parameters in the resolution process …

Closing thoughts

I’m honest with you. I consider ScreenSubject to be one of the most valuable patterns I’ve learned so far while playing with the StoryTeller sources. It provides such a nice extension point for screen initialization. I think it’s one of those patterns you don’t know how much you miss it until you see it for the first time and recognize how much it could have helped you in the past. At least that was my reaction. In the past I’ve put a lot of the functionality which resides in StoryTeller in ScreenSubject implementations on my screens which polluted my screens with a lot of initialization code and sometimes (especially when you have high network latency) doesn’t even really look good (I bet you know what I’m talking about, don’t you? I bet a lot of you have seen the frozen screen, too). The ScreenSubject pattern was introduced to my project last week and what can I say: I’m pretty happy to have it in our application ;-)

Pimp My CAB, or How to Integrate an Existing IoC With SCSF

A LITTLE WARNING: This post goes pretty deep into the CAB framework without examining the CAB basics. If you’re unfamiliar with CAB or SCSF this post is probably not going to be very handy for you …

My current project uses the Smart Client Software Factory which is build on top of the Composite UI Application Block from Microsofts Patterns & Practices department. SCSF is an organizational standard at my current client and we’re reusing some components of earlier projects (Large Parts of the Shell, Changetracking model etc.)

CAB is build around a very simple Dependency Injection machinery called the ObjectBuilder. I consider having the ObjectBuilder a good thing, compared to having no Dependency Injection at all. However if you’ve ever worked with any other IoC be it StructureMap, Unity, Windsor, NInject or some other container, you’ll recognize pretty fast some limitations. Its dependency injection mechanism

  • can’t really be used without attributes.
  • doesn’t separate registration and creation very well, which often leads to ordering problems.
  • can’t close open generic types. If you’ve ever used generic specialization you’re going to miss this.
  • is pretty tightly coupled to the concept of WorkItems inside CAB.

The last point is actually the real pain point for me. The whole WorkItem API is way to general purpose and generic (meaning string based!!!) in many parts and actually not the kind of concept I would like to be a central piece of my application design. It’s not intuitive to work with it and imho doesn’t fall into the pit of success at all.

Interestingly when you compare PRISM (which was also build by P&P about two years later) to CAB you’re going to recognize that the concept of WorkItems is completely missing in PRISM. Maybe I’m not the only one who feels that way. Our team decided very early that the whole contact area of our application to the CAB framework should be limited to the presentation layer. We wanted to use a fully fledged IoC on the lower layers. This lead to an intersting challenge: How to integrate those two pipelines? My initial thought was to replace the CreationStrategy used in CABs Builder class with something that reaches into our main container. This turned out not to be the best choice since a lot of CABs internal structure kind of relates to the standard behavior. I got something working for about half of the use cases, but it didn’t really feel good.

You know the best ideas come up when you stand under the shower. At least this happened yesterday. Actually integrating those two things is pretty straight forward. I just needed to approach the problem differently. CAB is build around attributes. A typical CAB service might look like this.

A service using CAB
1
2
3
4
5
6
public class NavigationService
{
  public NavigationService([ServiceDependency] IShell shell)
  {
  }
}

The ServiceDependencyAttribute tells the ObjectBuilder that it should get the dependency from the collection of services associated with the related WorkItem used to create the class. The interesting part is that this isn’t a marker attribute. It’s a fully fledged extension point to which the ObjectBuilder delegates the essential work of resolving an instance.

Here’s the deal: You can write a custom tailored attribute which is called by the ObjectBuilder but uses your main IoC in order to resolve the dependency

The implementation of this is actually pretty easy. Here are the steps you need to implement.

1. Create a Static Gateway into your container

Attributes are by their nature kind of static and created by the framework. In order to be able to call into my container from an attribute I created a static class which holds a reference to my container (You can of course also use the P&P CommonServiceLocator for this).

Create a static gateway into your container
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static class Container
{
  private static IContainer _container;

  public static void SetContainer(IContainer container)
  {
    _container = container;
  }

  public static void object Resolve(Type type)
  {
    return _container.Resolve(type);
  }
}

2. Create an attribute deriving from ParameterAttribute

The responsibility of ParameterAttributes in the ObjectBuilder is pretty limited. All they have to do is to create an implementation of the IParameter interface which will than be used to do the actual resolving. If you’re wondering what the membertype is, that’s the type of the parameter marked with the attribute (in the example code above this would be IShell). The CreateParameter method will automatically be called by the ObjectBuilder during the creation process.

Creating a custom ParameterAttribute
1
2
3
4
5
6
7
public class ContainerDependencyAttribute : ParameterAttribute
{
  public override IParameter CreateParameter(Type memberType)
  {
    return new ContainerParameter(memberType);
  }
}

3. Create an implementation of IParameter which calls into your static gateway

The IParameter interface defines two methods GetParameterType and GetValue.

The IParameter interface
1
2
3
4
5
public interface IParameter
{
  Type GetParameterType(IBuilderContext buildContext);
  object Getvalue(IBuilderContext buildContext);
}

We simply implement the first one with returning the member type and the the second one with a call into our Gateway.

A parameter that calls into our container
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class ContainerParameter : IParameter
{
  private Type _typeToResolve;

  public ContainerParameter(Type typeToResolve)
  {
    _typeToResolve = typeToResolve;
  }

  public Type GetParameterType(IBuilderContext buildContext)
  {
    return _typeToResolve;
  }

  public object Getvalue(IBuilderContext buildContext)
  {
    return Container.Resolve(_typeToResolve);
  }
}

Here is an example how it is used

Using the new attribute
1
2
3
4
5
6
7
8
public class SomePresenter
{
  public SomePresenter(
    [ServiceDependency] INavigationService navigationService,
    [ContainerDependency] ISomeService someService)
  {
  }
}

At least for us, this works like a charm. What I like about the solution is that it plays nicely by the rules of the CAB framework and doesn’t fight the framework design, but still enables us to use the framework in a way we want to use it. The interesting aspect in this approach is that you’re now able to haved mixed dependencies where one part is resolved using the surrounding CAB WorkItem and the other part is resolved using your container of choice. The whole attribute usage is limited to the presentation layer while the rest of the application can take advantage of fully fledged dependency injection without attribute, with generic specicialization and dynamic proxy generation, just to name a few options.

Implementing the Notification Pattern Using DataAnnotation Validators

Some weeks ago a friend of mine told me about System.ComponentModel.DataAnnotations. It’s a relatively new addition to the framework, mainly Asp.net related (mh, was it Mvc or Asp.net Dynamic Data? I’m sure he told me, but I can’t remember). Although I’m more focussed on client side development (WinForms + WPF), what he told me made me curious enough to spend some time with it in order to investigate whether the DataAnnotation framework could be reused for validation in a desktop app.

Background

What I was particulary interested in was whether I could use it in order to implement some sort of declarative validation (for most of the standard cases) on my WPF ViewModels. The usage I wanted to achieve was something similar to the code shown in the next listing.

A ViewModel with valiation annotations
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class CustomerViewModel
{
     private IValidator<CustomerViewModel> _validator;
     private NotificationCollection _notifications;

     [Required]
     [MinLenght(3)]
     [DisplayName("First name")]
     public string FirstName { get; set; }

     [Required]
     [MinLenght(3)]
     [DisplayName("Last name")]
     public string LastName  { get; set; }

     [Required(ErrorMessage="The field Email address is mandatory")]
     [ValidEmail]
     [DisplayName("Email address")]
     public string EmailAddress { get; set; }

     public CustomerViewModel(IValidator<CustomerViewModel> validator)
     {
            _validator = validator;
            _notifications = new NotificationCollection();
     }

     public NotificationCollection Notifications { get { return _notifications;}}

     public bool IsValid()
     {
            _notifications.Clear();
            _validator.Validate(this, _notifications);
            return _notifications.ContainsErrors;
     }
}

Here is what I came up with in order to use the DataAnnotation Validators for this

First of all, some basics. I’m going to demonstrate a (very simple) implementation of the Notification pattern in this post. A detailed explanation this pattern is a bit out of scope for this post, but here’re some excellent resources for that:

We’re starting with a base class for our Notifications. It’s a simple abstract class containing a message and a Source property. Besides that it contains an implicit conversion to string.

Our notification abstraction
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public abstract class Notification
{
     private readonly string _message;

     protected Notification() : this(string.Empty, string.Empty)
     {
     }

     protected Notification(string message) : this(string.Empty, message)
     {
            _message = message;
     }

     protected Notification(string source, string message)
     {
            Require.ArgumentNotNull(source, "source");
            Require.ArgumentNotNull(message, "message");

            _message = message;
            Source = source;
     }

     public string Source { get; protected set; }

     public override string ToString()
     {
            return _message;
     }

     public static implicit operator string(Notification notification)
     {
            return notification.ToString();
     }
}

Error is a simple class derived from Notification, which contains no additional code.

Representing an error as a class
1
2
3
4
5
6
public class Error : Notification
{
     public Error(string source, string message) : base(source, message) { }

     public Error(string message) : base(message) { }
}

I’ve seen some people implementing the Notification pattern with a single Notification class and an enumeration specifying the type of the Notification (Error, Warning, Info, etc.) but I prever using classes for this. I think readability is way better (and shorter) using classes. Decide for yourself:

Class based vs enumeration based implementation
1
2
3
bool isError = notification is Error;
//versus
bool isError = notification.Severity == Severity.Error;

It’s very rare that you only have to validate one element / property. Mostly we’re dealing with more than one elment beeing validated. Because of that it’s useful to have a container or collection for Notifications. This gives you a nice place for some additional functionality.

A container for Notifications
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class NotificationCollection : ObservableCollection<Notification>
{
     public bool ContainsErrors
     {
            get { return this.Exists(notification => notification.IsOfType<Error>()); }
     }

     public bool ContainsWarnings
     {
            get { return this.Exists(notification => notification.IsOfType<Warning>()); }
     }

     public IEnumerable<Notification> AllNotificationsFor(string nameOfSource)
     {
            return this.Where(notification => string.Equals(notification.Source, nameOfSource, StringComparison.Ordinal));
     }
}

While the first properties are pretty obvious, the last method probably needs some explanation. It finds all notifications for a given source name. The source in my implementation is the name of the property on the ViewModel that was validated. Im currently using a little convention here. Properties in WPF views have the same name as the ViewModel properties they’re bound to. This makes it relatively easy to correlate those two things (meaning deciding which Notification belongs to which UIElement). Having set this up, let me walk you through the validator implementation.

A Validator using DataAnnotations

A dedicated Validator
1
2
3
4
5
6
7
8
9
10
11
12
public class Validator<TElement> : IValidator<TElement>
{
     private static readonly IEnumerable<PropertyValidator> Validators;

     static Validator()
     {
            var properties = typeof (TElement).GetProperties(BindingFlags.Instance | BindingFlags.Public);

            Validators = from property in properties
                   where property.IsMarkedWith<ValidationAttribute>()
                   select new PropertyValidator(property);
     }

The static constructor of the Validator<TElement> class uses reflection to find all marked properties of the target type specified via the generic type argument TElement. It searches for properties marked at least with one derivate of the System.ComponentModel.DataAnnotations.ValidationAttribute and creates a PropertyValidator for each match.

Validating an element
1
2
3
4
5
6
7
8
#region IValidator<TElement> Members

public void Validate(TElement element, NotificationCollection notifications)
{
     Validators.Each(entry => entry.Validate(element, notifications));
}

#endregion

The actual validation happens inside the Validate method. This method simply uses all known PropertyValidators in order to validate the target object.

The PropertyValidator class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#region Nested type: PropertyValidator

private class PropertyValidator : IValidator
{
     private readonly PropertyInfo _property;
     private readonly string _propertyDisplayName;
     private readonly IEnumerable _propertyValidators;

     public PropertyValidator(PropertyInfo property)
     {
            _property = property;
            _propertyDisplayName = GetDisplayName(_property);
            _propertyValidators = GetValidators(property);
     }

A PropertyValidator does some things internally when it’s created. First it determines the name for the validated element which should be used in the UI. Since you probably don’t want the user to see something like “FirstName is required” or “SelectedCountry is required” I’m using System.ComponentModel.Design.DisplayNameAttribute here which can be used to specify a UI-friendly name. If no DisplayNameAttribute is specified on a property the validator uses the property name instead.

Getting the name that is displayed for a property
1
2
3
4
5
6
7
8
9
private static string GetDisplayName(PropertyInfo property)
{
     if (property.IsMarkedWith<DisplayNameAttribute>())
     {
            return property.GetAttribute<DisplayNameAttribute>().DisplayName;
     }

     return property.Name;
}

After it has determined the UI friendly display name it extracts all DataAnnotations ValidationAttributes from the property. (Note: GetAttributes is an ExtensionMethod. Same applies to IsMarkedWith and GetAttribute)

Extracting all DataAnnotation validators
1
2
3
4
private static IEnumerable<ValidationAttribute> GetValidators(PropertyInfo property)
{
     return property.GetAttributes<ValidationAttribute>();
}

And here is the rest, which brings the whole thing to life. This code simply extracts the value from the property, iterates over all known ValidationAttributes and checks the value with them. When a ValidationAttribute signals that a value is not valid, an error message is formatted with the UI-friendly name I talked earlier about and the whole thing is stored as an Error.

Validating an element
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#region IValidator Members

public void Validate(TElement element, NotificationCollection notifications)
{
     var value = _property.GetValue(element, new object[] {});

     _propertyValidators.Each(validator =>
     {
            if (!validator.IsValid(value))
            {
                   string formmattedErrorMessage = validator.FormatErrorMessage(_propertyDisplayName);
                   notifications.Add(new Error(_property.Name, formmattedErrorMessage));
            }
     });
}

#endregion

Bottom line

It’s pretty easy to combine the existing functionality provided by DataAnnotations with the Notification Pattern. It just took me an hour to get to a working solution which I consider pretty fast and which imho indicates an easy to use framework. As you can imagine the hard part isn’t getting the Notifications out of the model, but rather finding an unrepetative, intuitive way to display them in the UI. In the past I’ve missed several times the pit of success regarding this aspect. However I’m really confident that my current solution is really Dry AND easy to use. In one of the next posts I’m going to show how to combine Attached Behavior, Styles and Templates in order to bring the Notifications described in this post to the applications front door, the UI …

Diving Into the StoryTeller Trunk, Part 8: The ScreenCollection

Welcome back again to the “Diving into the StoryTeller trunk” series. Got your diving suit on? If so, good. If not: Suit-up! (Sorry, the HIMYM fanboy in me was too strong ;-))

Last time we spend some time with the concept of Screens. Screens more or less provide the content of an application. Content needs to be displayed somewhere and that’s where the ScreenCollection concept comes into play.

In abstract a ScreenCollection is a container for multiple Screens. It’s used to display screens. The ScreenCollection concept is comparable to PRISMs Regions or CABs WorkSpaces. It doesn’t really contain a lot of intelligence. It only allows you to add a Screen, remove a Screen, getting all Screens in the container, make a Screen the active one. You know, all in all the typical stuff you would expect from a collection (maybe except the last one). The ScreenCollection contract is represented by the IScreenCollection interface which looks like this:

The IScreenCollection interface
1
2
3
4
5
6
7
8
9
10
public interface IScreenCollection
{
      void ClearAll();
      IScreen Active { get; }
      void Show(IScreen screen);
      void Add(IScreen screen);
      void Remove(IScreen screen);
      IEnumerable<IScreen> AllScreens { get; }
      void RenameTab(IScreen screen, string name);
 }

If take a closer look at the interface you’ve probably recognized the last method which doesn’t really fit in there. Let’s spare that discussion for a moment. I’m going to comment on that in a moment.

StoryTeller contains only one implementation for the IScreenCollection interface, which is called (what-a-surprise) ScreenCollection. This class simply wraps around a standard WPF TabControl. Let’s take a look at how this is implemented, starting with the constructor.

StoryTellers ScreenCollection class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class ScreenCollection : IScreenCollection
{
   private readonly Cache<IScreen, StoryTellerTabItem> _tabItems = new Cache<IScreen, StoryTellerTabItem>();
   private readonly TabControl _tabs;

   public ScreenCollection(TabControl tabs, IEventAggregator events)
   {
       _tabs = tabs;
       _tabItems.OnMissing = screen => new StoryTellerTabItem(screen, events);
       _tabs.SelectionChanged += (s, c) => { events.SendMessage<UserScreenActivation>(); };

       // Hack.  Sigh.
       events.AddListener(new RenameTestHandler(new ScreenFinder(this), this));
   }

  ...
}

There’re are two interesting things to notice here. The ScreenCollection uses a cache concept in order to correlate Screens and the TabItems used to display them. The Cache<TKey,TValue> class is a smart wrapper around an IDictionary<TKey,TValue> which (besides some other functionality) allows you to plug-in a custom handler which is called when no value is found for the specified key. This handler acts as a kind of value factory. That’s exactly what we see when we take a look at the line with _tabItems.OnMissing. Each time a Screen is not found in the cache StoryTeller creates a new StoryTellerTabItem.

The other interesting thing to notice is that the ScreenCollection doesn’t directly expose events but rather uses the Eventbroker for this. You can see this at the UserScreenActivation message.

Yeah and then there is the “RenameTab” thing. It’s marked as a hack. It simply shouldn’t be there. The problem it currently solves it that when a test is renamed the related TabHeader must also be updated (We take a look at the TabItem in a moment). I wonder whether this isn’t something that could be done in a cleaner way using WPF databinding on Screen.Title instead.

Lets take a look at how the cache magic is used. It’s really compact code. Most of the methods are one or two liners.

Methods of the ScreenCollection class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public void ClearAll()
{
    _tabs.Items.Clear();
}

public void Show(IScreen screen)
{
    _tabs.SelectedItem = _tabItems[screen];
}

public void Add(IScreen screen)
{
    _tabs.Items.Add(_tabItems[screen]);
}

public void Remove(IScreen screen)
{
    TabItem tabItem = _tabItems[screen];
    _tabItems.Remove(screen);
    _tabs.Items.Remove(tabItem);
}

public IEnumerable<IScreen> AllScreens { get { return new List<IScreen>(_tabItems.Keys()); } }

The cache class is used like you would use a good old Hashtable. All in all I think I don’t need to say more here. Here is the code for determining the active Screen.

Determining the active Screen
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public IScreen Active
{
    get
    {
        if (_tabs.SelectedItem != null) return toScreen(_tabs.SelectedItem);

        return null;
    }
}

private IScreen toScreen(object tab)
{
    return tab.As<TabItem>().Tag.As<IScreen>();
}

Last but not least here’s the code for the TabItem which is build around a screen.

The StoryTellerTabItem class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class StoryTellerTabItem : TabItem
{
    private Label _label;

    public StoryTellerTabItem(IScreen screen, IEventAggregator events)
    {
        Func<Action<IScreenConductor>, Action> sendMessage = a => () => events.SendMessage(a);

        Header = new StackPanel().Horizontal()
            .AddText(screen.Title, x => _label = x)
            .IconButton(Icon.Close, sendMessage(s => s.Close(screen)), b => b.SmallerImages());

        Content = new DockPanel().With(screen.View);
        Tag = screen;

        ContextMenu = new ContextMenu().Configure(o =>
        {
            o.AddItem("Close", sendMessage(s => s.Close(screen)));
            o.AddItem("Close All But This", sendMessage(s => s.CloseAllBut(screen)));
            o.AddItem("Close All", sendMessage(s => s.CloseAll()));
        });
    }

    public string HeaderText { get { return _label.Content as string; } set { _label.Content = value; } }
}

I need to talk more about this part, don’t I? Again two intersting things here. First thing, it really makes heavy usage of C#3.0. You can see a lot of Extension Methods on WPF classes used in order to build and configure WPF elements in a very fluent and compact way.

Besides that you see here again how the EventBroker can be nicely integrated into Screen handling. Take a look at the context menu of each TabItem. It provides handlers which call directly into the EventBroker for triggering the typical close operations you can also see in Visual Studio. The important thing here to take away is that the close operations are only triggered here but performed by the IScreenConductor.

For those of you who didn’t follow my “StoryTeller” investigations from the start: The ScreenConductor is the great coordinator for the Screen Activation Lifecycle behind the scenes. It’s (as far as I can tell) the central facade to the Screen Activation Lifecyle from the perspective of typical application code. The ScreenConductor is a big topic which will be discussed in one of the next posts.

Closing thoughts

Lets not comment on the RenameTab thing, ok? I bet, Jeremy is going to fix that pretty soon. The ScreenCollection is (again) a good example of how much you can do with so few lines. However sometimes this can have downsides, too. I can only imagine .NET developers unfamiliar with this heavy usage of C#3.0 features staring at the code and thinking something like: WTF, what’s happening here? Personally, I like it, especially the cache aspect of it. I’ve done the .Tag thing far too often now.

Sadly one thing I would have loved to see is missing in the code, the ability to block deactivation or activation. Typical example for this is a requirement forcing the user to save or discard changed data before leaving a Screen. I had this requirement in the last 5 applications I worked on. It would have been interesting to see how Jeremy tackles such a requirement. I’m just assuming that he would use the EventBroker for that …

Enought Screen Mania for today. I hope you’ve enjoyed the ride so far and we’ll rejoin next time when it’s time to take a look at the big guy in the game, the ScreenConductor.

The Attached Behavior Pattern

With new technologies often completely new patterns emerge as people try to check-out how far a technology might take them. One interesting example for this is the Attached Behavior Pattern which seems to get a lot of attention in the WPF and Silverlight community lately. It’s a great example of what you can do with those technologies that was previously only very hard to achieve (although sometimes in my calm moments it feels a little bit like a hack to me).

Anyway, here is what the pattern actually does:

The Attached Behavior Pattern uses the moment when an attached DependencyProperty is attached to a DependencyObject in order to wire event handlers to it. With this you’re able to extend the behavior of elements in the WPF trees with arbitrary code.

Let’s take a look at how this can be achieved. First of all we need a class deriving from DependencyObject in order to be able to provide an attached DependencyProperty. It uses the standard pattern of registering the IsEnabled DependencyProperty in the static constructor (which is a bit clunky, btw).

A behavior must derive from DependencyObject
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class MyBehavior : DependencyObject
{
    public static readonly DependencyProperty IsEnabledProperty;

    static MyBehavior ()
    {
        IsEnabledProperty = DependencyProperty.RegisterAttached(
            "IsEnabled", //Name of the property
            typeof(bool),//Type of the attached property
            typeof(MyBehavior),//Type of the class that provides the property
            new FrameworkPropertyMetadata(false)); //Default value
    }

    public bool IsEnabled
    {
        get { return this.GetValue<bool>(IsEnabledProperty); }
        set { SetValue(IsEnabledProperty, value); }
    }
}

Pretty standard stuff so far. However you can use another constructor of FrameworkPropertyMetdata in order to supply a callback which is called when the value of the attached property changes.

Registering for change notifications
1
2
3
4
5
IsEnabledProperty = DependencyProperty.RegisterAttached(
               "IsEnabled", //Name of the property
               typeof(bool),//Type of the attached property
               typeof(MyBehavior),//Type of the class that provides the property
               new FrameworkPropertyMetadata(false, OnBehaviorEnabled)); //Default value + Callback

Next thing we need to do is to configure this attached property on the DependencyObject we want to attach behavior to. This is preferably done in XAML. You’ve got at least two options for doing the configuration. The first option is to set your attached property in the XAML file of a UserControl, Page or Window directly at the source, the element you want to attach behavior to.

Wiring it via XAML
1
<TextBox myNamespace:MyBehavior.IsEnabled="true" />

The other option is to use the the power of styles (an area were WPF really shines imho) in order to set it for all elements to which a style is applied.

Wiring it via XAML and styles
1
2
3
<Style TargetType="TextBox">
   <Setter Property="myNamespace:MyBehavior.IsEnabled" Value="true" />
</Style>

Personally I very much vote for the second option, because it enables you to specify the attached behavior in a single place in contrast to configuring it at several places in your solution. Don’t repeat yourself, unless you really need to.

Now, fasten your seatbelts. This is were the fun begins. When the WPF / Silverlight infrastructure loads the compiled baml from the resources and builds the element tree from it (and with this attaches our new property to the specified elements) the callback method gets called.

Attaching to the target instance
1
2
3
4
5
6
7
8
9
10
11
12
private static void OnBehaviorEnabled(
    DependencyObject dependencyObject,
    DependencyPropertyChangedEventArgs args)
{
    TextBox textBox = (TextBox)dependencyObject;

    textBox.LostFocus += (s,e) =>
    {
      //Put your little piece of magic here
    };

}

With first parameter of the callback you get a reference to the DependencyObject to which our attached property has been attached to. You’re now able to wire all sort of event handlers to the DependencyObject and are able to execute arbitrary code when the event occurs.

Here ends our journey for today. Attached Behaviors is a really nice technique which enabled me to do something that I always wanted to have in my WinForms apps but never found a satisfiing way to implement it (just a bit patience, I’m going to blog about it soon). I think it will be interesting to see how this pattern is used in the future. While new patterns always have the tendency to be overused, I think that this particular pattern can enable lots of valuable things …

WPF Is Not WinForms

I’ve been investing a lot of time in learning WPF lately. WPF has always been somehow interesting to me, however I never found actually the time to learn it from the ground up. I’ve been trying to grok it for several weeks know and am now slowly coming to a point were I can feel the ROI, start seeing the big picture (how the whole WPF architecture fits together) and what’s the really beneficial side of WPF compared to WinForms.

I’ve read several times about how steep the learning curve is and must admit, yeah that’s probably right. At least I’ve experienced it that way. BUT, here is the interesting side node: That’s mostly not because of the difficulty or complexity of the technology itself. A lot of my problems arose because of the way how I tried to approach WPF. Having spend most of my professional work with WinForms seems to have left some traces. I remember lots and lots of situations where I thought to myself: “Why is that so hard? In WinForms you must simply …”, “This TreeView just plain sucks” or “Mh, where is the Dock property on a Control?”.

Makes me smile now when I think about it. What I basically experienced is THAT IT’S HARD TO DO WINFORMS DEVELOPMENT WITH WPF. WPF was never designed to be WinForms V2. Neither was it designed to have a similar programming model. After realizing this here is a little yoda-eske advice for WPF-learners like me:

Don’t let you’re WinForms knowledge stand in your way. Try to really understand the programming model and the intentions of WPF first and constantly
review whether problems you experience while learning WPF come from trying to do the things the way you’re used to in WinForms.

Once I’ve understood that I really felt that I made a big leap forward. WPF is such a rich, enjoyable technology if you stick with it long enough. Sadly I’m currently not participating in a WPF or Silverlight project (like so may others), but I’ve high hopes. Better times are coming …