Fernando Machado Píriz's Blog

Posts about digital transformation, enterprise architecture and related topics

Archive for June 2010

The new Visualization and Modeling Feature Pack allows generating UML diagrams from code and vice versa

with one comment

Microsoft recently published the Visualization and Modeling Feature Pack for Visual Studio 2010. Download is available for MSDN subscribers here. The following (longly awaited) features are included:

  • Generate code from UML class diagrams.
  • Create UML class diagrams from code.
  • Import UML class, sequence, and use case elements from XMI 2.1 files.
  • Create and view links from work items to model elements.
  • Generate dependency graphs for ASP.NET Web, C, and C++ projects.
  • Create and validate layer diagrams for C and C++ code.
  • Write custom code to create, modify, and validate layer diagrams.

The following UML class diagram from Giving a Presentation was created using the Visualization and Modeling Feature Pack in just a couple of minutes:

ClassDiagram

Do you recognize how the Model View View Model pattern was used? It is easy from the diagram, is not it?

Written by fernandomachadopiriz

June 16, 2010 at 9:15 pm

A simple introduction to the Model View ViewModel pattern for building Silverlight and Windows Presentation Foundation applications

with 5 comments

Some time ago I was looking for a simple introduction to the Model View ViewModel pattern (also known as MVVM) and all the samples I was able to find were a bit complicated to my taste. I this post I will try to present you the MVVM pattern using the simplest possible example, focusing just on the key MVVM concepts. In other posts I will deep dive on other closely related concepts, but let us start with the basics.

MVVM is a successor of another well-known and very successful pattern so called Model View Controller (MVC). MVC was born (like many other well-known and successful patterns) in the Smalltalk world more than thirty years ago. Using MVC the application is composed by three kinds of objects, with very clear and differentiated responsibilities:

  • The model. Usually there is only one model per application. The model is responsible for all application’s data and related business logic.
  • The view or views. One or more representations for the end user of the application’s model. The view is responsible for showing data to end users and for allowing end users to manipulate application’s data.
  • The controller or controllers. Usually there is one controller per view, although it is not uncommon to see one controller per domain entity controlling multiple views. The controller is responsible for transferring data from the model to the associated view and vice versa. It is also responsible for implementing view’s behavior to respond to user actions.

image 

With MVC each type of object is responsible for just one thing, which simplifies developing, understanding and testing the code. In addition, it is easy to replace views, or to have more than one view of the same data.

In the case of Silverlight and Windows Presentation Foundation (SL/WPF) applications, the .NET framework provides the ability to use binding to transfer data to and from the view, so the controller is only responsible for implementing view’s behavior. In this case, the controller is called view model, leading to the MVVM pattern:

  • The model. Same as with MVC.
  • The view or views. Also the same as with MVC. Views are SL/WPF windows.
  • The view model. One view model per view. The view model is responsible for implementing view’s behavior to respond to user actions and for exposing model’s data in an “easy-to-bind” way to the view.

image

MVVC shares all of the benefits of MVC, but it has an additional benefit: the simplification resulting from using declarative binding to transfer data back and forth the view model to the view.

I will illustrate how MVVC works with an example. The code I will be using in this post comes from my sample application Giving a Presentation (although you are encouraged to download the installation file and the source code of Giving a Presentation from CodePlex, there is no need to do it in order to follow this post).

Giving a Presentation is a simple application to change certain setting while delivering a presentation, e.g., hide desktop icons, remove or replace desktop background, etc. Changes are reverted back when presentation ends.

The ability to change settings is provided by extensible parts and is not implemented in the application itself (more details in this post). So strictly speaking, the data Giving a Presentation deals with is just a boolean value indicating if the user is giving a presentation or not: the user sets the value on true when presentation starts, and set it back on false when presentation ends.

The model’s code is as follows. As promised, it is very simple; it has just a boolean property:

public class Model
{
    public bool GivingAPresentation { get; set; }
}

Here’s the view model’s code. It is also very simple. Like the model, it has a just a boolean property, whose value is get and set from an instance of the model.

public class MainViewModel
{
    private Model model;
    public bool GivingAPresentation
    {
        get { return model.GivingAPresentation; }
        set
        {
            model.GivingAPresentation = value;
        }
    }

    public MainViewModel()
    {
        this.model = new Model();
    }
}

The view (without any extensible part on it) looks like this:

image

The corresponding XAML code is:

<Window x:Class="GivingAPresentation.MainView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:GivingAPresentation "
        Title="Giving a Presentation" Height="350" Width="525" Icon="/MvvmDemo;component/Images/Presentation.ico">
    <Window.Resources>
        <vm:MainViewModel x:Key="mainViewModel"/>
    </Window.Resources>
    <Grid>
        <CheckBox Content="I'm currently giving a presentation"
                  HorizontalAlignment="Left" VerticalAlignment="Top" Margin="12,12,0,0"
                  IsChecked="{Binding Source={StaticResource mainViewModel}, Mode=TwoWay, Path=GivingAPresentation}" />
    </Grid>
</Window>

Interestingly, there is no code behind for this view[1] (furthermore, I have deleted the file MainView.xaml.cs from the project, and obviously the solution compiles and the application runs perfectly). Do you wonder why? Because there is no need to have any code in view’s code behind class; view’s behavior is coded in the view model, not in the view, do you remember?

The view is connected with the view model in three steps. First, an xmlns attribute in the Window node is used to alias the GivingAPresentation namespace as vm with xmlns:vm=”clr-namespace:GivingAPresentation. Second, an instance of the view model is created in the Window.Resources node; the name of the instance is declared with x:Key=”mainViewModel”. And finally, the IsChecked property of the view’s check box is binded with view model’s GivingAPresentation property with IsChecked=”{Binding Source={StaticResource mainViewModel}, Mode=TwoWay, Path=GivingAPresentation}”.

And that’s it. WPF/SL does the magic of getting check box’s state from view model’s property value, which in turn is taken from the corresponding model’s property value. WPF/SL also does the magic of setting view model’s property value whenever the user checks or unchecks the check box. The view model propagates property value change to the corresponding property in the model. Through this chain, a change in the view is reflected in the model.

This example is perhaps too basic, but it has all the key components of the MVVM pattern, and clearly shows the basis for implementing WPF/SL applications using that pattern.

What is next? There many things, very common in real world scenarios, not resolved at all in this very simple demo; for example:

  1. Not only the view, but probably other objects need to be aware of changes in view model’s properties values. That is where the INotifyPropertyChanged interface comes in to play. By firing a PropertyChanged event every time properties’ values change, other objects can react to these changes. It is worth to mention that those objects are not known by the view model, but will be notified anyway, thanks to the .NET Framework’s events infrastructure.
  2. It is very common for the view to ask its view model to execute certain actions. This can be achieved by the view model exposing commands, and the view binding control’s actions (like click) to those commands.
  3. It is also very common in real live applications to have interdependent views that need to communicate between them. To keep those views, and their associated view models, independent from each other, view models can use messages to communicate between them.
  4. Who creates who? In this simple demo the view declaratively creates the view model (in view’s XAML code), and the view model creates the model. In large applications, this approach is not always feasible, and you need other helper classes to manage objects creation.

These aspects are really not part of the MVVM pattern, but are actually needed to implement real world applications using WPF/SL; that is why you usually will see them covered together with the MVVM pattern in the literature. I plan to cover them in future posts, just to keep the MVVM basics, basic.

Hope you have enjoyed this explanation. Looking forward to see you soon. Bye.


[1] In this example. In Giving a Presentation’s real code, the view is responsible for presentation related tasks, like showing the notification icon when minimized for example, that requires code behind the view.

Written by fernandomachadopiriz

June 10, 2010 at 12:41 am