El evento online Windows Day: “Tecnologí­a para derribar paredes” acaba de empezar!

Windows Day

Para los que no saben de qué se trata este evento, una breve descripción tomada del blog del evento:

Descubre novedades acerca de las tecnologías de implementación, administración y de desarrollo de aplicaciones en desktops con Windows Vista y con Windows 7: cómo mejorar el rendimiento, cuándo virtualizar, cómo optimizar los escritorios, incrementar la seguridad, resolver el acceso a datos y cómo crear las mejores interfaces de usuario. Conoce todas las novedades que llegan con el SP2 de Windows Vista y lo que se viene con Windows 7 y ASP.NET 4.0. Conferencias online, demos y chat en vivo con expertos para dominar las últimas tecnologí­as en desarrollo de aplicaciones Windows (y web también).

 

Junto al gran Miguel Ángel Saez, estaremos presentando la siguiente sesión:

Sesión MSDN-1: Dando el salto hacia el presente con Windows Presentation Foundation

Conceptos necesarios para la creación de aplicaciones de negocio, que distinguen a WPF de otras tecnologías: Estilos, DataBinding, el patrón Presentation Model y los controles DataGrid y Ribbon.

Vamos a estar introduciendo Windows Presentation Foundation (WPF), haciendo hincapié sobre el lado técnico y de arquitectura de WPF, especialmente dirigido a desarrolladores que vienen de tecnologías clásicas como WinForms, y están tanteando la madurez de WPF como plataforma de aplicaciones de negocio.

También, como pueden ver de la descripción, y como no podía ser de otra manera, vamos a estar introduciendo el patrón Presentation Model, también conocido como Model-View-ViewModel (o M-V-VM), del cual ya he escrito varios posts en inglés.

Para la demostración del uso de este patrón, estaremos utilizando una versión simplificada de la aplicación de referencia de Prism (proyecto que les recomiendo mirar si piensan crear aplicaciones de negocio complejas): Stock Trader RI.

Prism 2.0 Stock Trader Reference Implementation

 

Las conferencias y demos son pre-grabadas, por lo que podrás verlas en el orden y en el momento que desees, y habrá más de 50 importantes expertos de todo Latinoamérica chateando contigo en las sesiones en vivo; y en exclusiva, una sesión en vivo con Mark Russinovich.

Accede al evento aquí­: http://www.microsoft.com/latam/windowsday/

Cualquier consulta, no duden en consultarme por medio de este blog. Espero que les resulte interesante y les haga dar el salto a WPF!

I finally got some slack time to put a small sample of Presentation Models with DataTemplates on WPF together. As I mentioned in a previous post, the combination between Presentation Model and DataTemplates can become a differentiated quality feature in your source code.
Let’s explore the sample (download link on the bottom).

image

The application is based on the Commanding QuickStart we shipped in the first release of the Composite Application Guidance for WPF (a.k.a. Prism or CompositeWPF). The original QS was written using presentation models, but without using automatic DataTemplates, so I updated it to create this sample.

I did not change the basic structure of the solution or the code so much, so you can compare it with the one shipped with Prism. The post assumes familiarity with the Composite Application Library (CAL) included in CompositeWPF, so I won’t get into much detail on things like the Bootstrapper, Regions, Modules, IoC Containers or Commands.

image

Notice how the solution does not contain any UserControl for the views. The only Window here is Shell (in the Commanding project), but it is basically empty, except for some properties like size or background.

So if the Shell window is empty. How does the application expose the main regions for the modules to start adding views? Well, in the Commanding Bootstrapper of course.

1 class CommandingBootstrapper : UnityBootstrapper

2 {

3   protected override DependencyObject CreateShell()

4   {

5      Shell shell = Container.Resolve<Shell>();

6      shell.Content = Container.Resolve<ShellPresentationModel>();

7      shell.Show();

8      return shell;

9   }

10  //…

11 }

So there in line 6 we inject the ShellPresentationModel into the Shell window, and we have our first DataTemplate view injected automatically in the Visual Tree (remember that the presentation model is not a control, and is lookless). The view template is declared in ShellResourceDictionary.xaml and included in App.xaml.

1 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

2 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

3 xmlns:local="clr-namespace:Commanding">

4   <DataTemplate DataType="{x:Type local:ShellPresentationModel}">

5    <Grid>

6    <Grid.RowDefinitions> … </Grid.RowDefinitions>

11     <ItemsControl ItemsSource="{Binding GlobalCommandsRegion.Views}" />

13     <ItemsControl ItemsSource="{Binding MainRegion.Views}" />

18   </Grid>

19  </DataTemplate>

20 </ResourceDictionary>

I stripped most of the styling parts. Notice that there is no RegionManager.RegionName attached property here. Instead there is a binding in ItemsSource to some MainRegion.Views property path in the ShellPresentationModel (the DataContext of the template is the instance of the DataType).

If we look into this ViewModel, you can see the regions being registered in the Region Manager and exposed to the View.

1 public class ShellPresentationModel

2 {

3   public ShellPresentationModel(IRegionManager regionManager)

4   {

5     MainRegion = new Region();

6     GlobalCommandsRegion = new Region();

7     regionManager.Regions.Add("MainRegion", MainRegion);

8     regionManager.Regions.Add("GlobalCommandsRegion", GlobalCommandsRegion);

9    }

10

11  public IRegion MainRegion { get; private set; }

12  public IRegion GlobalCommandsRegion { get; private set; }

13}

This keeps the composition at the Presentation Model level, instead of the UI being responsible of registering the regions.

One drawback of this particular implementation is that if I have a more complex Control that not only binds, but interacts with a region, there is no out-of-the-box behavior that will use Region Adapters to enhance this binding (in the example the ItemsControl just binds to the Views collection exposed by the region and that’s it).

But don’t discard this approach prematurely; if you need such a behavior, it could be easily solved by creating an attached behavior other than RegionManager.RegionName (BTW, this attached property IS an attached behavior…) that takes an existing region in the model and hooks it up with the target Control appropriately.

Now that the shell piece is ready to be used by CAL modules, let’s look at the OrderModule class.

1 public class OrderModule : IModule

2 {

3-11

12  public void Initialize()

13  {

14    RegisterResources();

15

16    IRegion mainRegion = regionManager.Regions["MainRegion"];

17    mainRegion.Add(container.Resolve<OrdersEditorPresentationModel>());

18

19    IRegion globalCommandsRegion = regionManager.Regions["GlobalCommandsRegion"];

20    globalCommandsRegion.Add(container.Resolve<OrdersToolbarPresentationModel>());

21   }

22

23   private static void RegisterResources()

24   {

25     ResourceDictionary dictionary = new ResourceDictionary();

26     dictionary.Source = new Uri("pack://application:,,,/Commanding.Modules.Order;Component/OrdersResourceDictionary.xaml");

27     Application.Current.Resources.MergedDictionaries.Add(dictionary);

28   }

29 }

As you can see, the first thing the Initialize method does is register the resources, by merging the Application’s resources with the OrdersResourceDictionary.xaml file. This allows having the resource dictionary files in the modules they belong. If you want to include the resources in the App.xaml file, you need to place the referenced files in the main project, making the idea of modularity senseless. More on this in my previous post.

Then the Initialize method adds the presentation models (as opposed to the Views in the original QuickStart) to the regions in order for WPF to "show" them, by automatically injecting the correct template defined in the resource dictionary.

If you dig into the OrdersResourceDictionary.xaml file, you’ll find some DataTemplates for the presentation models, and also some styles, converters and templates used to show validation errors in the the view. These are there to show that not only trivial views can benefit of this pattern, but also views that has some UI logic that is not a simple binding of a textbox.

And if converters are not enough for your templates, don’t hesitate on adding attached behaviors to cover the lack of code-behind gap, and still keep testability and reusability to the maximum.

My opinion on converters: just because they exist and can be very helpful, try to keep these in low numbers, and, instead, expose properties in the presentation models that can be easily bound to. Even if you can test these converters separately from the views, they can start to make your code less intuitive. Nevertheless, try to keep a balance and create a presentation model that is at the same time agnostic of the view that will represent it, but easily bound from a view (which is the purpose of a presentation model).

As you develop the views, you’ll notice the importance of commands to execute logic in the presentation models, as you cannot handle the Click event in the code-behind. In this example we’re not using the RoutedCommands that come with WPF, but another implementation (DelegateCommand) that is included in CompositeWPF. You can also use attached behaviors that end up invoking commands or actions on the presentation model in response to other control events.

Download the code to get into the implementation details for the views.

Disclaimer

This code is provided "AS IS" with no warranties. You can use it freely. It includes the binaries of Composite Application Library and Unity Application Block.

Download

Download the Presentation Model with Prism Sample (for Visual Studio 2008).

kick it on DotNetKicks.com

Silverlight has many things in common with WPF, but also many different or missing things because it is a “subset” of it.

One of the missing things is support for the ICommand interface (UPDATE: in Silverlight 2, this interface was included, but there is no implementation that uses it, so this post is still useful and the sample was updated to use Silverlight’s interface instead of my own copy of it from WPF). I find this interface (and the button’s behavior when bound to a command) extremely useful/necessary, especially when using DataTemplates bound to a Presentation Model (to provide the view for the model), as hooking events (like Click) is not an option in this scenario.

<Button Content="Save" Command="{Binding SaveOrderCommand}" />

As you might suspect, we (at p&p) are now spiking and seeing how the Composite Application Library for WPF (a.k.a. Prism or CompositeWPF) would work on Silverlight. One important part of the guidance provided is to use Commands for communication between the moving parts, and from the view (this is specially useful for testability).

Today the team published a small drop that contains some of the spikes we’ve been playing with, including an initial quick & dirt port of the library. We added the ICommand interface that is missing from WPF to the same System.Windows.Input namespace, not only to avoid adding new using statements all throughout the solutions, but in my opinion, because we hope Silverlight might support this out-of-the-box in the future, and we might be able to quickly switch to the provided implementation easily if they stay consistent with WPF’s API. (UPDATE: the interface is now part of Silverlight 2)

namespace System.Windows.Input
{
    public interface ICommand
    {
        bool CanExecute(object parameter);
        void Execute(object parameter);
        event EventHandler CanExecuteChanged;
    }
}

Once the ICommand interface is there, the DelegateCommand and CompositeCommand implementations included in CompositeWPF start working immediately and I can now call command.Execute(null) on my commands… big deal! But I want to hook my buttons to those commands from XAML!

public class DelegateCommand<T> : ICommand { ... }

Well, how to hook to a command using XAML? easy: using attached behaviors. First, I need to define an attached property that will contain the command.

public static readonly DependencyProperty CommandProperty =
    DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(Commands),
    new PropertyMetadata(CommandPropertyChanged));

Ok, I can attach the command to a button, but how will it be invoked when the button is clicked? Well, that’s when CommandPropertyChanged kicks in (and that’s why it’s an attached behavior, and not just a simple attached property):

private static void CommandPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
    ButtonBase element = o as ButtonBase;
    if (element != null)
    {
        if (e.OldValue != null)
        {
            CommandButtonBehavior behavior = (CommandButtonBehavior)element.GetValue(CommandButtonBehaviorProperty);
            behavior.Detach();
            element.SetValue(CommandButtonBehaviorProperty, behavior);
        }
        if (e.NewValue != null)
        {
            CommandButtonBehavior behavior = new CommandButtonBehavior(element, (ICommand)e.NewValue));
            behavior.Attach();
            element.ClearValue(CommandButtonBehaviorProperty);
        }
    }
}

The code above creates an instance of a behavior class that contains the behavior. This instance is stored in a private attached property, in order to be able to retrieve the behavior and Detach it when unhooking the command (when e.OldValue is not null).

The following code shows how CommandButtonBehavior hooks to the Click event of the Button in order to invoke the command.

private class CommandButtonBehavior
{
    private readonly WeakReference elementReference;
    private readonly ICommand command;

    public CommandButtonBehavior(ButtonBase element, ICommand command)
    {
        this.elementReference = new WeakReference(element);
        this.command = command;
    }

    public void Attach()
    {
        ButtonBase element = GetElement();
        if (element != null)
        {
            element.Click += element_Clicked;
        }
    }

    public void Detach()
    {
        ButtonBase element = GetElement();
        if (element != null)
        {
            element.Click -= element_Clicked;
        }
    }

    private static void element_Clicked(object sender, EventArgs e)
    {
        DependencyObject element = (DependencyObject)sender;
        ICommand command = (ICommand)element.GetValue(CommandProperty);
        object commandParameter = element.GetValue(CommandParameterProperty);
        command.Execute(commandParameter);
    }

    private ButtonBase GetElement()
    {
        return elementReference.Target as ButtonBase;
    }
}

The reason for storing the button as a WeakReference, is to avoid the application from leaking memory when trying to destroy a view with a button that has not correctly unhooked the command.

Ok, I believe that this bunch of code might be helpful, but how to use it from XAML? Again, easy:

<Button Content="Save" Commands:Commands.Command="{Binding Path=SaveOrderCommand}" />

As you can see, this looks way too similar to how WPF commands are declared, except for the Commands:Commands part of it, because this is an attached property and not a direct dependency property of the Button class.

I’m attaching a sample that uses the classes published in Codeplex by the Prism team. The sample includes support for CommandParameter and allows enabling and disabling the button depending on whether the ICommand.CanExecute method returns true or false.

image

Note: Even if I’m using DelegateCommand, you could use your own implementation of ICommand, as the attached behavior is not coupled to any implementation of ICommand.

Disclaimer

This code is provided “AS IS” with no warranties, and confers no rights.

Download

You can get the sample with the attached behaviors from here (updated for SL 2 RTW), or you can download the code for the behaviors without the sample from the latest change set of the CompositeWPF source control, in the spikes folder.

More information

Nikhil Kothari has a great introduction and samples for attached behaviors on Silverlight here.

John Gossman blogs about attached behaviors on WPF (here and here).

Dave Relyea created a neat example of attached behavior on Silverlight here.

Ezequiel Jadib has more info on the spike published in Codeplex here.

Shout it

In my previous post I talked a little of a new way that WPF allows us to create (and inject) a view by using DataTemplates (or ControlTemplates). I talked about how the use of templates combined with the Presentation Model pattern can help you build fully testable applications.

I was contrasting the benefits of using Presentation Model against the Passive View’s flavor of the MVP pattern when using it in the WPF world. I want to clarify that the Stock Trader reference implementation that’s being shown with the Prism project is not using Passive View (it was in the very first drop, but not anymore)… it has a mix of MVP with Supervising Controller (as of today).

The spike made by the Prism team that I was talking about was released here (get the zip, and the spike is under the PublishedSpikes folder).

The spike was based on the existing UIComposition QuickStart, so not all the code there is related to DataTemplates (as I said, it is just a spike and not production code, but we thought it would be interesting to put it out there). You are very welcomed to check it out. I won’t use the same example as the spike in this post, as I want to focus only on the templating part and leave the rest out.

One very neat thing about using templates, is whenever you add a model into the Visual Tree, WPF will automatically inject the view (template), assign the model as it’s DataContext and render it on screen. How? Well, let’s see an example.

You first need to create the DataTemplate you want to use:

<DataTemplate DataType=”{x:Type models:OrderModel}”>
  <StackPanel>
   
<Grid>
     

      <Label Grid.Row=”0″ Grid.Column=”0″>Customer Name</Label>
     
<TextBox Grid.Row=”0″ Grid.Column=”1″ Text=”{Binding CustomerName}” />
   
</Grid>
   
<TabControl ItemsSource=”{Binding LineModels}” />
    
<Button Command=”{Binding SubmitOrder}”>Submit</Button>
 
</StackPanel>
</DataTemplate>

You could place this portion of XAML in the App.xaml as a resource, but if you do this for every view in one centralized place, that file can get very big, hard to read, hard to manage, and what is worst, all devs or designers will try to edit that file constantly at the same time. Furthermore, if you’re developing different modules (like what you could do with Prism), you will not be able to deploy the modules independently.

Best option: create separate ResourceDictionary files where you can put one or a few tamplates grouped logically. Later on, you can merge these resource dictionaries by using MergedDictionaries in the App.xaml as explained here.

“Ok now, but if I’m using Prism, I cannot accomplish decoupled modules if now my application class has to know about all the resource files in all my modules!”. Fortunately, all that can be done in XAML can be done programatically, so instead of using MergedDictionaries on App.xaml, you could have your Module initialization logic to merge the isolated dictionaries into the application wide ResourceDictionary. In the spike published by the Prism team, this is done with the following code:

ResourceDictionary dictionary = new ResourceDictionary();
dictionary.Source = new Uri(“pack://application:,,,/OrdersModule;Component/OrdersRD.xaml”);
Application.Current.Resources.MergedDictionaries.Add(dictionary);

Now that the initialization has being done, all you need to do is “show” this model. For example:

Window mainWindow = new Window();
mainWindow.Content = new OrderModel();
mainWindow.Show();

On the next posts I’ll try to gather a downloadable sample, and show how to use commands to work in these scenarios. Also I’ll show how to use two-way bindings to communicate actions from the view to the model when commands are not enough.

kick it on DotNetKicks.com

In this post (of what may become a series of posts if I find some interest from the community) I compare 2 different approaches for separating view code from business logic in order to reduce the untested surface area while doing TDD.

The Passive View pattern

I have been using the Model View Presenter (MVP) pattern (or more specifically the Passive View pattern) for a long time now, both in the Winforms and WebForms worlds.

The main reasons for this? Testability and separation of concerns. As a TDD adopter, I want to be able to unit test as much logic as I can.

Passive View works fairly well, allowing me to keep the view (usually in the form of a user control) somewhat thin in order to satisfy myself without testing it (you know how difficult/impossible it becomes to unit test a UI screen).

In practice, applications written using Passive View end up having lots of boiler plate code for the communication between the view and the presenter. It also makes it very prone to start putting more knowledge on the view than what I’d like, not only for laziness in trying to avoid forwarding messages (that require very simple processing) to the presenter, but also in some transformations needed to keep the presenter agnostic of the specifics of the UI implementation.

WPF templates to the rescue!

In the Prism project we’ve using the Passive View approach also, as a logical step to adopt WPF when you come from winforms / webforms.

In the last time, though, I have been becoming very fond of another approach that is very easy to implement now using the WPF templating and databinding capabilities that weren’t available before: the Presentation Model pattern. This has been also called Model-View-ViewModel by John Gossman / Dan Crevier (if you haven’t read their blog posts on this topic, you MUST read them).

What I would like to add/highlight in this approach is that in WPF you can enforce keeping your view extremely thin by avoiding the use of UserControls or UI-coupled controls. Instead, you can create DataTemplates of your Presentation Model classes, and those model instances are the objects you’ll add to your Window. When your model gets laid out in the visual tree, WPF will automatically pick up the correct template for that model, and render the model appropriately.

This approach relies extremely on data binding, because there is no code behind at all on the views, just XAML markup.

Most of the times I end up deriving my presentation models from DependencyObject to benefit a lot from dependency properties.

In some cases where UI complexity dictates it, the model may derive from Control instead. "What?!? a model deriving from a Control?". That was my first thought when I came to that possibility, but it was highly biased from my Winforms past. Controls (don’t mistake with UserControls) in WPF are totally lookless and do not rely on the UI, so they can be tested in isolation. To render the appropriate view you’ll need to create a default ControlTemplate (compared to a DataTemplate for plain objects or DependencyObjects). One big benefit about using Controls is that you can maintain a WPF logical tree of presentation models (there are some benefits about this which I won’t cover in this post).

I’m planning on providing you with some code samples in the future, but in the meantime guess what: The latest Prism code drop will be including a spike we did using this approach. You should check it out and see how it feels. Notice that this is just a spike and we are only releasing it in order to get feedback from you guys, and see what is the interest on seeing more of it.