Welcome to MSDN Blogs Sign in | Join | Help

One of the things I found a bit more challenging than it should have been is working with animations in Silverlight. Often people will resort to code behind and triggering animations from code. However, I don’t really like that approach, because animations are a form of visualization. Visualizations should be created by designers. And I don’t think designers should have to be able to write code. So I’m going to show a pure XAML – databinding based way to trigger animation, by using a very simple attached property.

This post is part of my series on MVVM.

<Back to intro>

<Back to ‘How to apply the ViewModel pattern to new windows’>

 

Why use animations?

Using animations is a double edged sword. On the one hand, when abused, they can create a very flashy, but totally unusable UI’s. For example, moving advertising banners on websites can make that website much less usable. They distract from the actual content and make it harder for users to find. On the other hand, when you use animations properly, it can really enhance the user experience. For example, in Windows, if you minimize a window, it doesn’t just vanish. You see it quickly shrink and move to the position on the taskbar where it was minimized to. That makes it easy to see what happened, and where to find your window when you want to get it back.

I typically use the following rules to judge if an animation is valuable:

  • Animations should call the attention of the users that something has happened and make it very clear what is happening.
  • Animations should never get in the way of the user:
    • Animations should not be distracting from what’s important.
    • Animations should not slow down the user. If the user has to wait until an animation is done, then the animation is hindering.

 

Who is responsible for animations?

Animations can be an important part of your application. Often animations should be triggered by Business Logic. For example, if your application has network connectivity and you detect that the internet connection is lost, you might wish to start an animation to get the attention of the users and notify them of this state change. In this case, you might argue that the logic (your VieowModel) should trigger the animation. However, animations are also a form of visualization. Often, they are closely tied to visual elements (because they will be animated). So that means the animations should live in the View.

If you start your animations in directly from your ViewModel, you are directly interacting with visual elements from your ViewModel. That means you are breaking the separation of concerns between the Visualization and the Logic of your UI. Basically, you are undoing the benefits of the ViewModel pattern.

When it comes to triggering animations from your ViewModel, I try to split the responsibility between the logical event and the visualization of the animation:

  • Logical Event that should trigger the animation:
    Your ViewModel should raise an event to notify a logical state change. This can either be a pure ‘event’, but it’s typically easier create an observable property (by implementing INotifyPropertyChanged on your VM). If the logical event occurs, you can change the value of that property on your ViewModel. This is something you can test in your Unit Test.
  • Animated visualization of the event:
    The View should define the animation, for example by defining a storyboard. This animation can easily be changed by a designer. Then to visualize the event and start the animation, the view should listen to the event or monitor the property for changes. When the property changes, the animation should be triggered.

You could use the Code-Behind of your views to do this wireup. However, I don’t really like that approach, because there are much simpler ways to do that. I’ll show you how to trigger animations purely from XAML using databinding.

Triggering animations from your ViewModel

First of all, you have to create a logical property on your ViewModel, that will change when the animation should be triggered.

I’m also demonstrating animations in several places in my sample application:

image

You can see 4 buttons, that demonstrate different aspects of working with ViewModels. When you click a button, the UI for that particular demo should come into View. However, because some of the UI pieces are used for different parts of the demo, I used animations to make it very clear what UI elements are added and removed when you enter a particular demo.

To enable these animations I followed the following steps:

Define a bindable property on your ViewModel

In my sample, I’ve defined a bindable property on my ViewModel, called “State” and a Command that can update the state. Clicking one of the buttons on my app should change the state and trigger an animation.

   1: // Public property that will change
   2: public string State
   3: {
   4:     get { return _state; }
   5:     set
   6:     {
   7:         if (_state == value)
   8:             return;
   9:         _state = value;
  10:  
  11:         OnPropertyChanged("State");
  12:     }
  13: }
  14:  
  15: // In my case, the command that will trigger the state change:
  16: public ICommand GoToStateCommand { get; private set; }
  17:  
  18: private void GoToState(string newState)
  19: {
  20:     this.State = newState;   
  21: }
  22:  
  23: // Create the command object that can trigger the state change
  24: GoToStateCommand = new DelegateCommand<string>(GoToState);

Define animation in my view

The actual animations are defined in the view itself. I decided to use the VisualStateManager for this, but there are other options. Then I’ve created 4 visual states, each corresponding to one of the buttons. Here you can see one example of that:

   1: <VisualState x:Name="SimpleViewModel">
   2:     <Storyboard>
   3:         <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="mealDetailsView" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)">
   4:             <EasingDoubleKeyFrame KeyTime="00:00:00.2000000" Value="592.667"/>
   5:         </DoubleAnimationUsingKeyFrames>
   6:         <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="mealDetailsView" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)">
   7:             <EasingDoubleKeyFrame KeyTime="00:00:00.2000000" Value="1022"/>
   8:         </DoubleAnimationUsingKeyFrames>
   9:     </Storyboard>
  10: </VisualState>

Trigger the animation when the state changes

Now that i have a property on my ViewModel that raises an INotifyPropertyChanged.PropertyChanged event and I have a storyboard in place, now I have to tie the two together. In WPF this is fairly simple, because you can use a DataTrigger to trigger the animation. However, in Silverlight, this does not work with ViewModels. So I’ve written a small class that allows you to use databinding to trigger animations. This is just an example of how you could accomplish this.

The VisualStateSetter has a bindable dependency property. When you set it to a certain string value, it will access the Visual State Manager and set the state to that string value. And because it’s a implemented as an attached property, you can apply it to any type of control.

   1: public class VisualStateSetter
   2: {
   3:  
   4:     public static readonly DependencyProperty StateProperty =
   5:         DependencyProperty.RegisterAttached("State", typeof(string), typeof(VisualStateSetter), new PropertyMetadata(StateChanged));
   6:  
   7:     public static void SetState(DependencyObject target, string state)
   8:     {
   9:         target.GetValue(StateProperty);
  10:     }
  11:  
  12:     public static string GetState(DependencyObject target)
  13:     {
  14:         return target.GetValue(StateProperty) as string;
  15:     }
  16:  
  17:     private static void StateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  18:     {
  19:         Control host = d as Control;
  20:  
  21:         if (host == null)
  22:             return;
  23:  
  24:         VisualStateManager.GoToState(host, e.NewValue as string, true);
  25:     }
  26: }

So this is what using the VisualStateSetter class looks like:

   1: <UserControl UI:VisualStateSetter.State="{Binding State}">
   2: <!-- The content of the control -->
   3: </UserControl>

Here you see me binding the State property of the ViewModel to the Visual States that are defined in my View.

Now it would have been cleaner to have a more logical property on my ViewModel, for example an Enum and implement a converter that converts the Enum values to the Visual States in my View. But that’s not very difficult to do, so I’ll leave that up to you ;)

 

Hope this helps you to trigger animations in your views from your ViewModels.

_Erwin

Today, we’ve put the first beta drop of the book ‘Guide for Claims based identity and access control’ online. You can find the beta of the guide at Codeplex. Over the next couple of weeks, we’ll keep placing new releases online, so keep looking.

So what are these ‘Claims’ and why create a whole guide about them? Simple, it will help you overcome the current password hell

Password Hell

It’s true.. almost website you go to wants to know who visits their site.

This is not just a problem for regular internet users, but it’s a massive problem for organizations. A typical organization will have a lot of applications, both internal for it’s own employees and external for customers. Now of course, there are authentication solutions for each scenario: Windows integrated authentication, Forms based authentication, smart cards, and many more solutions. Each with it’s particular advantages and disadvantages.

With each solution, you get an island of identities. An active directory here, a database with users there. Then a couple more when the organization merges or starts to cooperate with other organizations. And each user store has to be managed when new users are introduced, roles change or when people leave the organization. With typically many identity stores in an organization, this can easily become a management nightmare.

Claims based identity and access control

The goal of claims based identity and access control is, to abstract the authentication logic from applications and and let somebody we trust handle that. We do it all the time.

A passport is a typical ‘real world’ example of a claim.

Passports without claims

For some countries, you need a visa to enter. That means going to the embassy and request a visa to enter that country. If you can provide sufficient reason to want to enter that country, you’ll receive your visa within several weeks. If you loose your visa, you can replace it. It will just take you several weeks again.

Sound familiar? That’s how a typical website works nowadays. You can sign up and get a password. Sometimes you can get a password automatically, but sometimes it has to be created manually. And if you loose it, you’ll have to request a new one.

Passport as a claim

Fortunately, to most countries, you can travel without a visa. That’s because those countries trust each other to a certain degree. If you come with a certified valid document (your passport), and the country you are trying to enter trusts your country, then they will typically let you in. And since the passports are protected with all kinds of forgery protection tricks, it’s very hard to create a fake passport.

This looks like claims bases authentication. A trusted party can issue claims (a passport) and your application can decide if you trust claims from that trusted party or not. Because the claims are digitally signed, it’s nearly impossible to tamper with them. One example of this is single sign-on, such as with OpenID or a Live-ID.

Claims based authentication

Claims based authentication is not new. It’s been around for many years. But with the introduction of open standards and Microsoft technologies like Geneva it becomes a lot easier to implement.

Goal of the guide

Authentication touches a lot of people within your organization. Architects, developers, IT-pros, security experts. Each contribute a piece to the whole authentication story. The goal of the guide is, to make claims based authentication and access control understandable for everybody.

So how are we doing that? A clear, scenario based approach with lot’s of samples.

Yes, now YOU can also take advantage of claims based authentication

As always, we’re open to feedback. Let us know what you think and make a difference!

[Update] This is part 1 of this post. Read the second post here.

At the end of building prism V2, we have played around with different application styles to see how easy it is to consume our own libraries. In this blog post, I’m going to describe my attempt at creating an outlook style application. My implementation shows the following aspects:

  • How to create application parts that can be activated and deactivated, can be put in a list, and are very lightweight.
  • How to use an Application Model?
  • How to do pure ViewModel first development. In WPF, you can apply implicit Data Templates to visualize objects, but in silverlight that doesn’t work. So I’ll demonstrate two ways to do this.
  • How to handle RegionContext in a more direct way.

You can download the Source Code here:

<Outlook style app>

You will need the following references to make the solution work:

Download prism, compile it, and place the binaries in the lib folder. Also, place the Unity binaries in the lib folder.

Requirements

So what are my requirements for the outlook style app.

  • Be able to show a list of buttons that can activate parts of an application (like the outlook buttons for Mail, calendar, contacts, etc.)
  • It should be possible to activate and deactivate ‘Application parts’. If an application part becomes active, It’s initial view should show up in the main area.
  • Only one ‘application part’ can be active at any point in time.
  • When a view or an application part becomes active or inactive, other views might also have to be added or removed, such as toolbars.
  • Show a list of available ‘application parts’, without really instantiating all their views immediately. Only instantiate the views the first time you show them.

Solution

So this is my Outlook style app:

image

With a little bit of imagination, I hope you can see how this app could resemble outlook ;)

The following diagram shows the overall structure of the application and the most important pieces.

image

My shell has several regions, each brightly colored to make it clear where they are.

The ApplicationModel defines that the application has a list of UseCases. The ButtonBar (in red) is bound to the list of use cases. Each use case is represented as a button. When you click that button, the ActivateUseCase command is fired which will activate the selected UseCase.

An UseCase (like the MainEmailUseCase) implements the IActiveAwareUseCaseController and likely inherits from ActiveAwareUseCaseController. This makes it activatable (I know, it’s not a word). Lastly, the EmailUseCase itself defines which views it needs and where those views should go.

In the following paragraphs, i’m going to describe some of the moving pieces of this design.

Application model

The approach I took when creating the OutlookStyle app is to have a central ‘application model’ that knows how the application is structured. The modules also know a bit about this application model, through the IApplicationModel interface.

The ApplicationModel has a list of Main Usecases (more on usecases later), that I could bind my list of buttons to. It also has a command that can activate a UseCase when one of the buttons is clicked.

Using an ApplicationModel is kind of a double edged sword. It ties you somewhat down to a specific style of application. This makes your modules less portable, but it also makes the interaction between your modules and your shell more explicit and thus easier to understand. Using an application model is only one approach to creating an outlook style application and there are many others. But I thought it was an elegant solution and since we weren’t showing how to create an ApplicationModel in the Prism RI or the Quickstarts I thought it would be nice to show it here.

Internally, the application model uses a SingleActiveRegion to store the UseCases. This might seem strange, but a Region is nothing more than a model that can store a collection of objects that can be added, removed and activated. The SingleActiveRegion is ideal for this purpose, because it will make sure only one usecase is active at a given time. I choose not to add the region to a regionmanager, because I want the ApplicationModel to control access to this region.

 

Showing application parts: UseCaseControllers.

My implementation for the ‘application parts’ that can be activated and deactivated are called ‘UseCaseControllers’. This were my requirements for them:

  • I want to be able to put it in a list bind a collection of buttons to
  • I want to be able to activate and deactivate it.
  • It should be very lightweight, because all available controllers will be activated at once.

Motivations for naming the ‘application parts’

It was quite hard to find a right name for the ‘application parts’:

  • It’s not a module, because a module will likely contain many application parts. Also, a module should be viewed as a unit of deployment.
  • It’s not a view, because it’s more likely a set of views, working together to fulfill a single use case. These views, can be main views, tool bars, etc..
  • I considered the term ‘feature’ for a while. However, if you have ever built installers, you’ll know that a feature is also an overloaded term. It also refers more to a unit of deployment than what we’re looking for here.

So called my ‘Application parts’ UseCaseControllers. In my example, the main buttons on the outlook app kind of map to the ‘main’ or initial UseCases in my application.

Why call it controller? Controller is quite an overloaded term, because of the Model View Controller pattern. However, controllers are also commonly used to coordinate some kind of process and couple several pieces together to form a single unit. So because the controller hooks several controls together to perform a single use case, I called it a UseCaseController.

ActiveAwareUseCaseController

The ActiveAwareUseCaseController is a handy base class that you can use to fulfill the IActiveAwareUseCaseController interface. It does the following things for you:

  • BeforeFirstActivation Method. Have a handy place for the first time you activate this controller. In this method (BeforeFirstActivation), you can create all your Views or ViewModels and perform any eventwiring. For example, tie any toolbar commands to your ViewModels. The ObjectFactory also helps with this.
  • ViewToRegionBinder. One of the things you are very likely to do is to add views to some regions when the UseCase becomes active, and remove them again when it becomes inactive. Instead of having to put region.Add(view) and matching region.Remove(view) calls in the activate and deactivate methods, I figured it would be handy to create one registration method that takes care of this.

Using the ViewToRegionBinder to add and remove views to and from regions

Adding and removing views from a region whenever something becomes active or inactive can be quite tedious. Whenever a view or usecase (or anything else that implements IActiveAware) becomes active, you probably have to find the right regions, add the views to the regions. And the same if the usecase is deactivated (but then remove the views)

To make this a bit easier, I have created the ViewToRegionBinder. This object can monitor an IActiveAware object (such as a IActiveAwareUseCaseController or a view or a ViewModel). You can register a list of objects (views or viewmodels) against names of regions so that, when the object you are monitoring becomes active, the views will be added to the right regions and removed when the object becomes inactive.

   1: // Make sure the Toolbar and the mainregion get displayed when this use case is activated
   2: // and removed again when it becomes inactive. 
   3: this.ViewToRegionBinder.Add("ToolbarRegion", this.emailToolBarViewModel);
   4: this.ViewToRegionBinder.Add("MainRegion", this.emailViewModel);

Using the ObjectFactory to delay creation of your views until you actually need them

Another interesting challenge I ran into was:I wanted to shows a list of buttons for each usecase in my system. But only when I click one of these buttons do I want my views to be created and initialized. You can imagine, if you have 20 of these ‘main’ usecases and each creates a bunch of views when the application starts, application load time would be dramatic.

This was one of the motivations for creating the UseCaseControllers in the first place. They are very lightweight and I could create the views I needed in the Activate() method. But then I faced an other issue. I really like to create my views and my viewmodels using Constructor Injection. However, since the objects injected the constructor would be created before the usecase would be created, not after, i had to put in some level of indirection.

This is what the ObjectFactory<Type> solves. You can express the dependency on an object in the constructor, and create the object when you need it, by calling the ObjectFactory.CreateInstance() method. You can access the instance created by the objectfactory using the ObjectFactory.Value property.

Now I didn’t want to create member variables for the ObjectFactories, because that would mean that every time I needed to access the view, i would have to go through the ObjectFactory.Value property. I really wanted to have variables of the type of the views. So I created the AddInitializationMethod, where you can add a lambda expression that will set the member variable for the views. The ActiveAwareUseCaseController will call these lambda’s just before the UseCase becomes active for the first time.

The following code snippet shows how this works in the MainEmailUseCase

   1: // The references to these viewmodels will be filled when the app is initialized for the first time. 
   2: private EmailMainViewModel emailViewModel;
   3: private EmailToolBarViewModel emailToolBarViewModel;
   4:  
   5: public EmailMainUseCase(
   6:     // Get the ViewToRegionBinder that the baseclass needs
   7:     IViewToRegionBinder viewtoToRegionBinder
   8:     // Get the factories that can create the viewmodels
   9:     , ObjectFactory<EmailMainViewModel> emailViewFactory
  10:     , ObjectFactory<EmailToolBarViewModel> emailToolBarFactory) : base(viewtoToRegionBinder)
  11: {
  12:     // Just before the view is initialized for the first time
  13:     this.AddInitializationMethods(
  14:             // Create the emailViewModel and assign it to this variable
  15:         () => this.emailViewModel = emailViewFactory.CreateInstance()
  16:             // Create the toolbarViewModel and assign it to this variable
  17:         , () => this.emailToolBarViewModel = emailToolBarFactory.CreateInstance());
  18: }

Why do I like Constructor Injection? It expresses very clearly what the dependencies of my object are, in a single place.  Take the previous code snippet. You can clearly see that the EmailUseCase has a dependency on the IViewToRegionBinder, the EmailMainViewModel and the EmailToolBarViewModel. Those are the only objects this class interacts with. Sure, in some cases it might seem easier to get a reference to the service locator and resolve types when you need them, but that makes it very unclear what other types your class depends on and also makes unit testing a lot harder.

 

Bootstrapper

As usual, the bootstrapper is the glue for all the individual pieces. In the bootstrapper, all the infrastructure pieces are registered in the right way, so the application can use them. You can see that I’m registering the types i need to the container and some of the default regionbehaviors to the RegionBehaviorFactory

 

What’s next?

In the Outlook style application, i’m also showing a bunch of other things:

  • How to do ViewModel First development in an elegant way.
  • How to use RegionContext in a bit easier way
  • How to show views in a popup in a robust way. Note, in the current version, this is still work in progress.

Since I’ve already spent way to much time on this blogpost, i’m going to address these things in future posts.

As always, I really appreciate your feedback. Any comments or questions are more than welcome.

Happy coding!

_Erwin

[Update: Also read part 2 of this post. ]

A colleague asked me a question today. How do you apply the Model View ViewModel pattern to new Windows and Popups. To illustrate that, i wrote a small sample app, which I wanted to share with you.

This post is part of a series:

<Back to intro>

<Back to ‘How do I adapt a simple vs complex viewModel’>

<Forward to ‘How to trigger animations from your ViewModel’>

There are usually two types of windows you might want to open. Modal windows, where the current window is no longer accessible until the modal window is closed, and non modal popups, where both the current window and the popup are opened and usable at the same time.

Modal windows

From the perspective of the ViewModel, opening another viewmodel in a popup is just like a very slow synchronous service. Take for example opening a confirmation dialog. The viewmodel doesn’t care if you ask the confirmation from a user, or from an external service. All it knows is that it needs the confirmation and has to wait until it get’s it.

The following codesnippet shows this:

   1: public class MainWindowViewModel : INotifyPropertyChanged
   2: {
   3:     //...
   4:  
   5:     // At a certain point in time, the MainViewModel want's to open a modal window
   6:     // pass it the number of the window and know the number of the window that was closed last. 
   7:     private void OpenDialogWindow()
   8:     {
   9:         // Create the viewmodel for the child window. This allows us to communicate
  10:         // with the window in the popup
  11:         var viewModel = new ChildViewModel();
  12:  
  13:         // pass the viewmodel some data: in this case, the number of the current window
  14:         viewModel.WindowNumber = ++WindowCount;
  15:     
  16:         // opening a modal dialog is like a synchronous service
  17:         _windowService.ShowViewModelInDialog<ChildView>(viewModel);
  18:  
  19:         // After the window is closed, get the number of the window that was just closed
  20:         LastWindowToBeClosed = viewModel.WindowNumber;
  21:     }
  22: }

You can see how the viewmodel askes a service (The WindowService) to show a particular viewmodel. To keep the implementation of the WindowService, i’m also passing the Template (ChildView) to use to visualize the View. But there are many different ways of solving this, for example the one I’ve demonstrated in my Outlook style sample.

The code for the WindowService is very simple:

   1: public class WindowService : IWindowService
   2: {
   3:     public bool? ShowViewModelInDialog<TViewType>(object viewModel)
   4:         where TViewType : Control, new()
   5:     {
   6:         Window w = new Window();
   7:         TViewType view = new TViewType();
   8:         view.DataContext = viewModel;
   9:         w.Content = view;
  10:         return w.ShowDialog();
  11:     }
  12: }

This is simply a generic way of showing a viewmodel in a window, by using a View to visualize the ViewModel and show the window as a dialog.

Non modal popups

Now in the case of a normal popup, it’s more like an asynchronous service. The code in the ViewModel can continue to execute, but the opened window can raise events to signal status changes. This is very similar to, for example, an asynchronous webservice, that raises events for progress changes or completion.

The following code snippet shows this:

   1: private void OpenPopupWindow()
   2: {
   3:     // Create the ViewModel to communicate with the service
   4:     var viewModel = new ChildViewModel();
   5:  
   6:     // Pass the ViewModel some information
   7:     viewModel.WindowNumber = ++WindowCount;
   8:  
   9:     // Opening a popup is like an asynchronous service. You can listen to change notification events
  10:     // such as the Closed Event i've implemented
  11:     _windowService.ShowViewModelInPopup<ChildView>(viewModel);
  12:  
  13:     // Listen for a change notification, when the window is closed
  14:     viewModel.Closed += viewModel_Closed;
  15: }
  16:  
  17: // This method is called when the window is closed again
  18: void viewModel_Closed(object sender, EventArgs e)
  19: {
  20:     // Get the information from the viewmodel
  21:     var viewModel = (sender as ChildViewModel);
  22:     this.LastWindowToBeClosed = viewModel.WindowNumber;
  23:  
  24:     // Unsubscribe from the event to prevent memory leaks
  25:     viewModel.Closed -= viewModel_Closed;   
  26: }

As you can see, the code is similar to the Modal example. The only difference is, that you have to sign up for an event to get the required information.

The WindowService is slightly more complicated in this case:

   1: public void ShowViewModelInPopup<TViewType>(object viewModel)
   2:     where TViewType : Control, new()
   3: {
   4:     Window window = new Window();
   5:     TViewType view = new TViewType();
   6:     view.DataContext = viewModel;
   7:     window.Content = view;
   8:  
   9:     // If the viewmodel knows about window closing events (IClosedAware) 
  10:     // then forward closing notifications to the viewModel;
  11:     SubScribeToClosedEvent(window, viewModel as IClosedAware);
  12:  
  13:     window.Show();
  14: }
  15:  
  16: private void SubScribeToClosedEvent(Window window, IClosedAware view)
  17: {
  18:     if (view == null)
  19:         return;
  20:  
  21:     window.Closed += (sender, args) => view.OnClosed();
  22: }

I wanted a generic way for the WindowService to notify a viewmodel if the window is closed. So I created the IClosedAware interface, and implemented that on the ViewModel. The WindowService will, if the viewModel implements the IClosedAware, sign up for the ClosedEvent of the window and notify the ViewModel if that event occurs.

Hopefully this explains the way you can work with several Windows when using MVVM.

A while back, I wrote an MSDN article on writing multi-targeted programs with Prism.

http://msdn.microsoft.com/en-us/magazine/ee321573.aspx 

Hope you like it!

When I started with separated presentation patterns, I always thought that to create a single screen, I ALWAYS had to create a view to display the data, a presenter/controller/viewmodel class to hold the logic and a model class to hold the data. Later, I learned that this was a too rigid way of thinking about these classes and that I had to take a more pragmatic approach. Not every model is the same, and so you might have to take different choices. Sometimes you can work with a very simple model, that’s very well suited to your views. Great.. but that requires a completely different approach from working with a complex model. This blog post goes into more details about working with different types of Models.

<Back to intro>

<Back to Implementing the Model View ViewModel pattern>

<Forward to working with multiple windows>

What is that model thingy?

A model is more than just a POCO class that holds data. I view the model more as the collection of classes that solve a particular business problem. This can include:

  • A Business entity that stores the data.
  • A Business component that holds business logic and operates on top of a business entity.
  • Classes that retrieve or persist the data, for example repositories, service agents, etc.

A colleague of mine told me the following analogy, which I thought was striking. The classic Model View Controller paradigm can be thought of as batch processingThe Controller handles the input from the user and how to respond to that input. The View handles everything related to showing the output to the user. So the model encompasses the data and all the processing that is done with that data.

So when you design your model, you should try to model it so it can optimally accommodate the business logic and business rules. The UI is not the only way you might want to have access to your business logic. For example, an import process or web service might need to call the same Business Logic as the UI. Also, you should be able to change the process followed in the UI, without affecting the data and the business logic your application works with. For example, to improve user experience, you might change a complex editing screen into a wizard or more graphically oriented editing.  If you modeled your Model around your UI, then you have to change your Model when the UI changes. When you have designed your Model around the business logic, then your ViewModel can adapt the model to the process the user follows.

Now of course there are tradeoff’s. If you have very little business logic, and the UI is the only consumer of the business logic, then it might make more sense to design the model to more closely match what you see on the screen.

 

Working with “easy to use” models

Sometimes, you have the fortune to get really easy to work with models. Easy to use models typically have the following characteristics:

  • They are easy to bind to.
    For example, they implement INotifyPropertyChanged for properties, ICollectionNotifyPropertyChanged for all collections of objects. Also, they might implement validation logic in a way that’s easily consumed by the UI, such as implementing IDataErrorInfo.
  • The model corresponds closely to what you see on the screen.
    If the model is very similar to the data on the UI. For example a Customer screen displays and edits all the fields from the Customer model object. In that case, there is very little need for data conversion or aggregation.

Usually, you’ll be working with a very easy to use model if you have full control of the design and implementation of the model. Then you can design the model to very closely fit the application scenario. Another situation where you’ll be working with easy models is if your application has little business logic and is mainly used for editing and displaying data.

Let’s consider the following example:

You’d like to display a view on the screen that displays information about a Meal and it’s Ingredients. You have designed the Model yourself and it will only be used for your application. Because of the way you designed the model, supports 2 way databinding and it’s very well suited to display things on the screen. However, there is some aggregate data, such as total calories that the model does not provide.

In this case, you can design your UI layer like this:

image 

The model itself contains most of the information that needs to be displayed on the screen, so the view can directly consume the model classes and show most of the information based on that. However, since there is some aggregate data and logic, you will need a viewmodel to hold that. Also, the viewmodel can hold UI state information that shouldn’t be present in the model, such as the currently selected ingredient.

As you can see, the IngredientsView doesn’t have a ViewModel of it’s own. It doesn’t have any logic of it’s own and can get all the information it needs from the Model. Then, it doesn’t make sense to create a separate ViewModel for that view. All the logic and the composition is handled by it’s parents.

So there are a couple of things you can do when you work with easy to bind models:

  • Consuming the model directly from the View
    If your Model exposes most of the data your view needs, then the view can directly consume the model. Be careful if your model changes often (IE, if you don’t have control over the model because it’s created and exposed by an other team or even other company). In that case, consider if it makes sense to absorb those changes in your ViewModel.
  • Don’t blindly create viewmodels for all of your views.
    If you don’t need one, because there is no Logic or UI state to hold, then don’t create one. However, if you find that you have some logic or UI state, then it definitely makes sense to create a simple ViewModel.

 

Working with “hard to use” models

Unfortunately, you don’t always have the luxury to work with models that are easy to work with. A hard to work with model has the following characteristics:

  • The model does not easily map to what you need in the UI. For example, the view needs to combine information from several models.
  • It does not allow two-way databinding.

This can happen if you don’t own the model. For example, you are consuming 3rd party web services or you are working with a database and model from a different application. In these cases, you often don’t have control over what he model looks like. Now you can solve the problem of compensating for a difficult model completely in the view, but that makes the view very complex. And since view code is very hard to test and is also very closely tied to the UI technology, this can quickly turn into a management nightmare. It’s much better to solve this problem in a separate, testable set of classes, that together form the ViewModel.

Lets consider an example again. Again you want to display information about how healthy a meal is. Unfortunately,  the meal and ingredient classes don’t contain this information, so a service called the MealPlanner is used to determine if a meal is healthy for you or not. In this case, the data from the model cannot be used directly.

image

In this case, the model is not suited well to show the required information from the screen. And because the Model is already used in many other parts of your application, it’s not easily changed. So a new data structure has to be created, to contain the aggregated information. This new datastructure, the MealViewModel and the IngredientViewModel, are now very well suited to display all the required information on the screen.

So, if you are working with harder to use models, you might have to create new datastructures that will hold data in a form that’s very easily consumed by the view.

I hope this makes the role of the models and the ViewModels a bit clearer.

In this third part of my series of blog posts on the ViewModel pattern, I’m going to demonstrate how to implement a simple example of the ViewModel pattern. Not to worry, we’ll dive into more exiting examples later.

<Back to intro>

<Back to: The difference between MVVM and other Separated presentation patterns>

<Next: Adapting a simple vs complex model>

The ViewModel

So what is a ViewModel? And how does it differ from a View or the Model. Consider the following example. Suppose you would build Paint using WPF or Silverlight, using the MVVM pattern:

image

The View obviously determines what is displayed on the Screen. And the Model, well that will likely be the Image. But the application works with more data than ‘just’ the Document. This extra data is mostly the State of the UI. What brush is currently selected? What is the ‘zoom’ percentage? While it is possible to store this information in the View itself, this is usually a bad practice. For example, the zoom slider bar could be the place where you would store the zoom percentage. However, when more elements on the screen need to use the Zoom percentage, this value quickly becomes very hard to manage.

Model for the View

The ViewModel is a model for the view. Therefore, it hold’s all the state of the view as well as the logic that operates on the state. The ViewModel exposes this data and logic in such a way that the View can very easily access it. However, the ViewModel should not expose or interact directly with UI elements. 

Another responsibility of the ViewModel is to adapt the Model to the View. Typically the Model is a domain model (we’ll dive into that more in a later blog post). If you have full control over the model, then typically you can build it so that the model itself is very easily databindable. However, if you don’t have control over the model, for example, you are getting it from an external system, then the ViewModel might need to adapt the model to the view. For example, by adding aggregations, combining information from different models or simply by implementing INotifyPropertyChanged to enable the ViewModel notifying the View that properties have changed.

The MVVM pattern

So the following picture shows the MVVM pattern as how you would typically implement it in WPF or Silverlight:

image

The View is typically implemented as a UserControl or DataTemplate (in WPF). It uses Databinding to read and update information on the ViewModel. For example, the ViewModel can expose a public property Name that can be bound to a textbox.

If the view needs to communicate to the ViewModel, there are several options:

Commands

To route the Click event from a button to a ViewModel, the easiest way is to implement a Command. The Command pattern describes an object that can invoke functionality at a later point in time. In this case, when the user clicks a button. We’ll dive into commands later in this post.

This defines the Commands in XAML:

   1: // Define the Commands
   2: public ICommand ShowCalorieKingInfoCommand { get; private set; }
   3: public ICommand ShowIngredientInfoCommand { get; private set; }
   4:  
   5: // Initialize the commands in the constructor with a delegate command.
   6: public MealDetailsViewModel(IDialogService dialogService)
   7: {
   8:     this.ShowCalorieKingInfoCommand = new DelegateCommand<object>(ShowMealCalorieKing);
   9:     this.ShowIngredientInfoCommand = new DelegateCommand<Ingredient>(ShowIngredientInfo, CanShowIngredientInfo);
  10: } 
  11:  
  12: // The methods called when the commands are invoked
  13: private void ShowMealCalorieKing(object notUsed) {..}
  14: private bool CanShowIngredientInfo(Ingredient selectedIngredient) {..}
  15: private void ShowIngredientInfo(Ingredient selectedIngredient) {..}

This snippet shows an example how to bind a command to a button in XAML

<Button Margin="10, 10, 10, 10" Content="Show information on CalorieKing.Com" 
Commands:Click.Command="{Binding ShowCalorieKingInfoCommand}"/>

Pretty much only buttons allow you to use Commands out of the box. Now it’s possible (and not too hard) to create your own commands using attached behaviors).

2 way bindable properties

You can also use TwoWay databinding to notify the ViewModel that something has changed. For example, the following codesnippet shows how the DataGrid Control has a SelectedItem property. If you TwoWay databind this property to a property on the ViewModel.

Here’s the property in C#:

   1: public Ingredient SelectedIngredient
   2: {
   3:     get { return _selectedIngredient; }
   4:     set
   5:     {
   6:         if (_selectedIngredient == value)
   7:             return;
   8:  
   9:         _selectedIngredient = value;
  10:         OnPropertyChanged("SelectedIngredient");
  11:     }
  12: }

You can see that it also supports the INotifyPropertyChanged event. This means that the View will be notified if this value is changed in the ViewModel. And this is what the XAML would look like:

<data:DataGrid ItemsSource="{Binding Meal.Ingredients}" 
SelectedItem="{Binding SelectedIngredient, Mode=TwoWay}" >
 
When I first started using the ViewModel pattern, I overlooked this capability. For example, I was looking for a way to attach functionality to the SelectedItemChanged event of the DataGrid. But two way databinding works a lot more directly. Just don’t forget to add the “Mode=TwoWay” tag ;)

Bind ViewModel methods to events from controls

The Caliburn framework allows you to bind public methods on the ViewModel directly to your controls in XAML. While this is a really cool technology, I also believe it makes your XAML more complex, because effectively, you are now programming (calling methods) in XAML. So I would personally try to either use commands, use two way databinding or implement an attached behavior (more on this subject later). 

Code behind

It is always possible to use Code Behind to communicate between the View and the ViewModel. Whether this is a good idea is a topic of hot debate. I personally am of the opinion that there are better ways to solve this problem than to use code behind. In a later blog post, I’ll go into details why i think this is a bad idea and how you can avoid this.  But there are people who think differently.

ICommand interface

A common way to expose functionality from your ViewModel that your Views can interact with is by exposing Command objects. A command object implements the ICommand interface.

The ICommand interface has two methods:

  • Execute, which will fire the logic encapsulated by the command
  • CanExecute, which determines if the command can actually execute.

The CanExecute is interesting. It’s a common scenario that you might wish to disable certain functionality, based on the state of your UI. This can easily be accomplished with a command. Because, when you bind a button to a command and CanExecute returns false, then the button will automatically become disabled.

Commands also have another advantage: They decouple the invocation from the actual logic. This allows for interesting scenario’s:

  • Binding multiple ui elements to a command
    Consider for example a SaveCommand. Often you don’t just have a Save Button, but also a Save menu item, and perhaps a save keyboard shortcut that will fire the same functionality. All these user gestures can be bound to the same command.
  • Chaining commands together
    You might also wish to bind several commands to a single UI element. For example, a certain type of ViewModel can expose a Save Command. However, you can have several instances of that ViewModel (with the corresponding view) open at any given time. A Save All button can be bound to all SaveCommands on all those ViewModels.

Silverlight doesn’t have Commanding support built in. Fortunately, it does support the ICommand interface, so there are several libraries available that provide Silverlight implementations of the ICommand interface. For example Prism (aka the Composite Application Guidance for WPF and Silverlight) and the MVVM Toolkit both provide a DelegateCommand implementation.

In my demo application, I’m also demonstrating the use of the DelegateCommand.

The INotifyPropertyChanged interface

One thing that you’ll find yourself implementing on your ViewModels the time is the INotifyPropertyChanged interface. This interface allows your ViewModel to notify the View of changes to properties.

This code snippet shows how to implement this pattern:

   1: // Public event (for the interface)
   2: public event PropertyChangedEventHandler PropertyChanged;
   3:  
   4: // Protected method for invoking the event from code
   5: protected virtual void OnPropertyChanged(string property)
   6: {
   7:     var handler = PropertyChanged;
   8:     if (handler != null)
   9:     {
  10:         handler(this, new PropertyChangedEventArgs(property));
  11:     }
  12: }
  13:  
  14: // Example property that triggers the property. 
  15: public Ingredient SelectedIngredient
  16:  {
  17:      get { return _selectedIngredient; }
  18:      set
  19:      {
  20:          // IMPORTANT: only trigger the event if someting actually changes!
  21:          if (_selectedIngredient == value)
  22:              return;
  23:  
  24:          _selectedIngredient = value;
  25:          OnPropertyChanged("SelectedIngredient");
  26:      }
  27:  }

One important thing: before invoking the event in the property, check if the value has actually changed. This helps preventing never ending loops when properties are chained together.

If you don’t like the repeating code you’ll get when implementing properties with INotifyPropertyChagned, you can also use ObservableObjects as properties, as I’m describing (among other things) in this blog post:

http://blogs.msdn.com/erwinvandervalk/archive/2009/04/29/how-to-build-an-outlook-style-application-with-prism-v2-part-2.aspx

 

What not to do in a ViewModel

There are a couple of things you shouldn’t do in your ViewModels:

  • Expose or interact with visual elements in your ViewModel
    Don’t try to expose Visual Elements, such as Buttons or other views from your ViewModel. This ties your UI to Visual Elements and makes it hard to test in isolation. Now you might run into the situation where your ViewModel needs to determine which view to display. In a later blogpost, i’ll describe how your ViewModel can be responsible for the logical ViewModel selection and use a DataTemplate to create the Visualization.
  • Try to control the View too directly from your ViewModel
    You should try to keep your ViewModel logical, rather than Visual. For example, if you want to color a control red in error situations, you could expose an “IsControlRed” property, or expose a brush in the red color. It’s usually better to expose the logical property, such as “HasError”. Then the UI designer can decide if the color of the control should be red or purple in an error situation.

Summary

This blog post describes the basics about implementing the MVVM pattern. In later blog posts, we’ll dive into more interesting scenario’s.

This is the second blog post in a series on the Model View ViewModel pattern. Before I’m going to dive into the details of the Model View ViewModel pattern, I thought it is handy to describe the differences and similarities between this pattern and other separated presentation patterns.

<Back to the intro>

<Next: Implement the Model View ViewModel pattern>

There are quite a number of Separated Presentation patterns out there. Model View Controller, Model View Presenter, Presentation Model, Passive View, Supervising Controller, Model- View-ViewModel and many many more:

image

When you look at these patterns, sure, the arrows are in different directions. But is that the only difference? Is a controller the same as a presenter or a presentation model? How would you compare Model View Presenter vs Model View ViewModel. In this blog post, I’m going to describe these differences and similarities between the most common separated presentation patterns.

Building an UI without Separated presentation patterns

How would you build a UI without using a separated presentation pattern. Typically, you’d create a form or user control, drag your controls on it and put the logic in the code behind. The code in the Code behind is very closely coupled to the UI, because it directly interacts with the controls on the screen. This approach is nice and straight forward, but only for really simple views. Because when the logic becomes more complicated, maintaining such a UI can become a nightmare!

The root of the problem lies in the fact that building a UI this way violates the single responsibility principle. This principle states: “A class should have only a single reason for change.” If a UI component has code for visualization, logic and data, it effectively has several reasons for changing. For example, if you wish to change the type of controls that are used to display the data, that change should not affect the logic. However, because the logic is so closely tied to the controls, it has to change too. This is a ‘code smell’ that signals that the single responsibility principle is violated.

So the Form or User Control holds both the code to draw the UI (controls, etc..), the logic of the UI (What happens when you click a button) and the data of the UI (The data that the UI works with), you’ll run into the following problems

  • Decreased Maintainability
    A change in either the UI, the logic or the data will most likely cause changes in the others. This makes it a lot harder to make changes and decreases maintainability of the UI.
  • Decreased Testability
    The logic and Data of an application can be written in such a way that each component can be unit tested in isolation. However, the UI related code is inherently very hard to Unit Test, because it often needs user interaction to trigger logic in the UI. Also, any visualization often needs to be judged by a human to see if it ‘looks right’. If the UI related code is mixed with Logic and Data, you loose the testability of the Logic and Data.  Note, there are automated UI testing solutions available. However, they ‘mimic’ the user interaction. They are typically harder to setup and maintain than unit tests, but also they are often only useable as integration tests, because they need the entire application to be set up. 
     
  • Decreased Reusability
    If your UI related code is mixed with logic and with data, it becomes a lot harder to make that code reusable.

 

The goals of separated presentation patterns

While the individual patterns are quite different, the goals of these patterns are actually quite similar. Separate UI related code (Views) from Logic related code (Presenters, Controllers, ViewModels, etc..) and from the Data (Models). This allows each of these to evolve independently. For example, you are able to change the Look and Feel of your application, without affecting the logic or the data.

Secondly because the Logic and Data is separated from the visualization, the logic and the data can be unit tested in isolation. For very straightforward applications, this might not be very significant. For example, if your application is a simple data editor. However, if you have more complicated UI logic, it will quickly become very valuable to be able to automatically verify that your UI logic works as expected.

 

Model View Controller pattern

One of the very first separated presentation patterns was the Model-View-Controller pattern. This pattern was developed by Trygve Reenskaug.

In 1979!!!! (I wasn’t even born then).

Anyway, this pattern was developed for building Smalltalk applications. But in those days, computer programming was a bit different than today. There was no Windows. No graphical user interface. No Controls library. If you wanted a UI, you had to draw it yourself. If you wanted to interact with input devices such as keyboards. (Where there even mice in those days?)

But what Trygve did was quite revolutionary. Where everybody was mixing the visualization code, User interaction code, logic and data together, he came up with a pattern to separate these into separate classes, each with a distinct responsibility.

The problem with the MVC pattern is that it’s very likely the most misunderstood pattern in the world. And I think it’s caused by the naming. Trygne originally called the pattern Model-View-Editor, but later settled on the name Model View Controller. Now I can understand what a Model is (data) and what a View is (Something i can look at, the UI). But what is a controller? Is an ‘Application Controller’ the same controller as the controller in the MVC pattern?  (No, but you can see where some of the confusion comes from)

image

So what are those Models, Views and Controllers

  • Model
    The model typically is the data of your application and the logic to retrieve and persist that data. Often, this is a domain model that can be based on a database or the results from web services. In some cases, that domain model maps perfectly to what you see on the screen, but in other cases it has to be adapted, aggregated or extended to be usable.
  • View
    The View was responsible for drawing the UI on the screen. Without windows or controls, that meant drawing, boxes, buttons, input fields, etc on the screen. The View can also monitor the model and display any data in it or update itself if the data changes.
  • Controller
    The controller is responsible for handling the User Input and then updating the Model or the View. So if the user is interacts with the application, IE: presses a button on the keyboard, moves the mouse, the controller is notified of that user gesture and decides what to do with it. Maybe it should update the view, maybe it should update the model.

I whipped up the following example to illustrate what a Controller would look like in a ‘pure’ MVC implementation. I happened to implement it in normal asp.net (not asp.net Mvc), but without relying on any of the controls. So it’s more traditional asp style. (Ok, I know this is not a pretty example, but I hope it gets the point across of what a controller was meant to do.)

   1: public class Controller
   2: {
   3:     private readonly IView _view;
   4:  
   5:     public Controller(IView view)
   6:     {
   7:         _view = view;
   8:  
   9:         HttpRequest request = HttpContext.Current.Request;
  10:         if (request.Form["ShowPerson"] == "1")
  11:         {
  12:             if (string.IsNullOrEmpty(request.Form["Id"]))
  13:             {
  14:                 ShowError("The ID was missing");
  15:                 return;
  16:             }
  17:  
  18:             ShowPerson(Convert.ToInt32(request.Form["Id"]));
  19:         }
  20:     }
  21:  
  22:     private void ShowError(string s)
  23:     {
  24:         _view.ShowError(s);
  25:     }
  26:  
  27:     private void ShowPerson(int Id)
  28:     {
  29:         var model = new Repository().GetModel(Id);
  30:  
  31:         _view.ShowPerson(model);
  32:     }
  33: }

After many years, the programming paradigm changed somewhat. The concept of a control emerged. A Control encapsulates both the visualization (It draws itself), but also the user interaction. A button knows what to do if you click it. A textbox knows what to do if you type text in it. This reduces the need for a controller, so the Model View Controller pattern became less relevant. However, since there was still a need for separating out the logic of the application from the Controls and the data, an other pattern called Model View Presenter became more popular.

Most examples of the MVC pattern focus on very small components, such as building a text box or building a button. With a bit more modern UI technologies (Visual basic 3 is modern compared to 1979 smalltalk), you typically don’t need to apply this pattern. Unless you are developing your own control using very low level API’s. For example, if you want to build a completely custom control using Direct X, then you might be interested in this pattern.

The last couple of years MVC pattern became very relevant again, but for a different reason, with the advent of the ASP.Net MVC framework. The ASP.Net MVC framework does not use the concept of controls in the same way as the normal ASP.NET framework does. In the ASP.Net MVC framework, a View is an ASPX control that renders HTML. And the controller again handles the user gestures, because it receives the HTTP requests. Based on the http request, it determines what to do (update a model or display a particular view).

 

Model View Presenter pattern

So after the rise of visual programming environments and the introduction of controls that encapsulated both the Visualization and the User Interaction code, the need for creating a separate controller class became less. But people still found the need for a form separated presentation, only this time at a higher abstraction level.  Because it turned out that if you create a form that is composed out of several controls and also contains the UI logic and the data, The Model View Presenter pattern describes a way to separate out the visual elements (Controls) from the Logic (What happens when you interact with the controls) and the Data (what data is displayed in the view).

image

  • Model
    The model typically is the data of your application and the logic to retrieve and persist that data. Often, this is a domain model that can be based on a database or the results from web services. In some cases, that domain model maps perfectly to what you see on the screen, but in other cases it has to be adapted, aggregated or extended to be usable.
  • View
    The View is typically a user control or form that combines several (smaller grained controls) into a (part of a) user interface. The user can interact with the controls in the View, but when some logic needs to be started, the view will delegate this to the presenter.
  • Presenter
    The presenter holds all the logic for the view and is responsible for synchronizing the model and the View. When the view notifies the presenter that the user has done something (for example, clicked a button), the presenter will then update the model and synchronize any changes between the Model and the View.

One important thing to mention is that the Presenter doesn’t communicate directly to the view. In stead, it communicates through an interface. This way, the presenter and the model can be tested in isolation.

There are two variations of this pattern, Passive View and Supervising Controller.

Passive View

In the passive view, the view knows nothing about the model, but instead exposes simple properties for all the information it wants to display on the screen.  The presenter will read information from the Model and update the properties from the model.

This would be an example of a passive view:

   1: public PersonalDataView : UserControl, IPersonalDataView
   2: {
   3:     TextBox _firstNameTextBox;
   4:  
   5:     public string FirstName
   6:     {
   7:         get
   8:         {
   9:             return _firstNameTextBox.Value;
  10:         }
  11:         set 
  12:         {
  13:             _firstNameTextBox.Value = value;
  14:         }
  15:     }
  16: }

As you can see, this requires quite a lot of coding, both for the View but also for the Presenter. However, it will make the interaction between the View and the Presenter more testable.

Supervising Controller

In supervising controller, the View DOES know about the Model and is responsible for databinding the model to the view. This makes the interaction between the Presenter and the View a lot less chatty, but at the expense of testability of the View-Presenter interaction. Personally i hate the fact that this pattern is called “Controller”. Because the controller is again not the same thing as the controller in the MVC pattern and also not the same as an “Application Controller”.

This would be an example of a view in the Supervising Controller.

   1: public class PersonalDataView : UserControl, IPersonalDataView
   2: {
   3:     protected TextBox _firstNameTextBox;
   4:  
   5:     public void SetPersonalData(PersonalData data)
   6:     {
   7:         _firstNameTextBox.Value = data.FirstName;
   8:     }
   9:  
  10:     public void UpdatePersonalData(PersonalData data)
  11:     {
  12:         data.FirstName = _firstNameTextBox.Value;
  13:     }
  14: }

As you can see, this interface is less granular and puts more responsibilities in the View.

Presentation Model

Martin Fowler describes a different approach on achieving separation of concerns on his site, that’s called Presentation Model. The Presentation Model is a logical representation of the User Interface, without relying on any visual elements.

image

The presentation model has several responsibilities:

  1. Hold the logic of the UI:
    Same as the Presenter, the Presentation Model holds the logic of the UI. When you click a button, that click is forwarded to the Presentation Model, which then decides what to do with it.
  2. Massage the data from the model to be displayed on the screen:
    The presentation model can convert the data in the model so it can more easily be displayed on the screen. Often, the information contained in the model cannot directly be used on the screen. You might need to alter the information (IE: convert data types),  enrich the information (IE: summations) or aggregate information from several sources. This is especially likely if you don’t have full control over the model. For example, you get information from an 3rd party web service, or from a database of an existing application.
  3. Store the state of the UI:
    Often, the UI needs to store additional information that has nothing to do with the domain model. For example, which item is currently selected on the screen? What validation errors have occurred? The presentation model can store this information in properties. 

The View can then easily read the information from the Presentation Model and get all the information it needs to display the view. One advantage of this approach is that you can create a logical and fully unit testable representation of your UI, without relying on testing visual elements.

The Presentation Model pattern doesn’t really describe how the view then uses the data in the Presentation Model.

Model View ViewModel

And then there is Model View ViewModel, also known as MVVM or just the ViewModel pattern. It looks surprisingly similar to the Presentation Model pattern:

image

In fact, the pretty much the only difference is the explicit use of the databinding capabilities of WPF and Silverlight. Not surprising, because John Gossman was one of the first persons to mention this pattern on his blog.

The ViewModel doesn’t communicate directly with the View. Instead it exposes easily bindable properties and methods (in the form of Commands). The View can databinding those properties and commands to query information from the ViewModel and call methods on the ViewModel. It’s also not required that the View knows about the ViewModel. XAML Databinding uses a form of reflection to bind properties of the ViewModel, so theoretically you can use any ViewModel with the View that exposes the right properties.

Some of the things I really like about this pattern when applied to Silverlight or WPF are:

  • You get a fully testable logical model of your application. I’ll talk more about this in further posts.
  • Because the View Model offers everything the view needs in easily consumed format, the view itself can be fairly simple. In fact, a designer can play with the look and feel in Expression Blend and change it without affecting the UI.
  • Lastly, you can avoid using code behind. In a later blog post, I’ll describe how to do this in more detail. Now this is a point of debate amongst View Model fans. I personally feel that you often don’t need code behind and that there are often better ways of solving it. Ok, sometimes you’ll need to do some tricks (like create attached behaviors) but they offer really nice and reusable solution. However, I also recognize that not everybody likes XAML markup and the XAML way of expressing databinding. The ViewModel pattern doesn’t force you to use or avoid code behind. Do what feels right to you.

Conclusion

I hope this description of the most common Separated Presentation patterns helps you in understanding their differences.

While building the Composite Application Guidance for WPF and Silverlight (AKA Prism V2), we relied heavily on the Model View ViewModel pattern. But while this pattern is definitely the best thing ever, it took me a while to come to grips with it:

First of all, I have a mostly Windows Forms and ASP.Net background. With these technologies, I typically applied different separated presentation patterns, such as Model View Presenter. So when I tried to build WPF and Silverlight applications, I tried to apply the same techniques. But what I found was, that building WPF and Silverlight applications is significantly different from those other technologies. When I tried to apply the Model View ViewModel pattern, I kept running into questions. How do I do “X” in this pattern.

At first glance, the Model View ViewModel does not differ that much from other separated patterns such as Model View Presenter. It certainly tries to achieve similar goals, but it does it in subtly different ways.

In this series of blog posts, I’m going to describe how to apply the Model View ViewModel pattern and what kind of challenges you’ll have to overcome and what kind of decisions you’ll have to make. Over the next couple of weeks, I’m going to be writing about these topics:

How do I:

(Inside the MVVM pattern)

(When applying the MVVM pattern to an application)

  • Instantiate my Views / ViewModels
  • Create a logical ViewModel structure of my application
  • Implement automatic datatemplate selection in Silverlight

Hope you’ll find these topics interesting. If there are specific things you are struggling with, let me know. If i have time, I’ll try to write something about that as well.

<Download demo app>

Note, you’ll need to download the following references:

As I’m publishing new blog posts, I’ll keep updating this app, so check back sometimes for updated versions..

Hi guys,

Sorry, it has been a bit silent on my blog. But for a good reason. For the last couple of months, I’ve been secretly working on a new project. And this thing is going to be HUGE! Bigger than windows! Prettier than the IPhone and far more influential than Google!

I must admit, I didn’t start this project alone. To be quite honest, my wife did most of the work!

And here she is:

 

Noé Larah

image

Isn’t she a treasure? Yes, i think I am the proudest daddy in the world :)

And if I’m not blogging as much in the next couple of weeks.. now you know why ;)

In a previous post, I mentioned that there are difficulties with using the Visual Studio extensions for Windows SharePoint Services (VSeWSS) in combination with interfaces. It turns out that this problem is not just limited to using base classes, but also to using base classes in different assemblies.

The problem:

Just a small recap of the problem i was facing:

I had placed an interface in a different assembly than the implementation. For example, we had created an interface for doing logging, the ILogger interface and had created a basic implementation for this interface. Our own reusable code was using this ILogger, however, we wanted users of our library to be able to create and plug in their own logger. To do that, they have to derrive from the ILogger interface. However, as soon as you would do this, your project wouldn’t package anymore.

While packaging, i got the following error:

Error    1    VSeWSS Service Error: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.

Although I don’t have a true solution for this problem, I do have a workaround. If the DLL that contains the baseclass is in the GAC, then VSeWSS can find it.

 

The workaround

I found that, if you placed the DLL’s that have the base classes and interfaces in the GAC, then VSeWSS can find them. It took me a while to find this out because if you run into this error and then add the DLL into the GAC, then you have to perform an IISReset before VSeWSS finds out that you have added it to the GAC.

I decided to add a post build script to remove and add my files to the GAC. One other challenge I ran into was, that GACUTIL.EXE is not in the same location on every machine. And there is no, easy to use environment variable to find it. So I created a small .BAT file to help me with this.

This is the content of the RegisterInGAC batch file:

 

set gacutil=%programfiles%\Microsoft SDKs\Windows\v6.0A\Bin\gacutil.exe

echo *** RegisterInGac.bat %1 %2
echo * Trying to find GacUtil.exe:

if not exist "%gacutil%" echo * Could not find GACUtil at: %gacutil% 
if not exist "%gacutil%" set gacutil=%ProgramW6432%\Microsoft SDKs\Windows\v6.0A\Bin\gacutil.exe
if not exist "%gacutil%" echo * Could not find GACUtil at: %gacutil%
if not exist "%gacutil%" goto error

echo * Using gacutil.exe from %gacutil%

call "%gacutil%" %1 %2
goto done

:error
echo * Warning: Could not (un)register %2 in the gac.

:done

You can see that it’s trying to find the GACUtil from several locations and it’s telling you which one it’s using.

And to get it to work, I placed this script in the Post build event:

image

My .BAT file is located a couple of levels up in my source tree, so I have to find it there.

Nice side-effect of this approach

I’ve found that there is a nice side-effect to using this approach.

Our packages are also placing some DLL’s into the GAC. However, because assemblies in the GAC take precedence over assemblies on the filesystem, this can cause issues when running unit tests. The unit test will not use the latest version (that you have just built), but it will use an older version that’s still in the GAC. By using this approach, you basically make sure that the version in the GAC is always the latest version.

Hope this helps.

Keep practicing!

Erwin

This week, we published the results of interation 9 to our codeplex site.

You can get it here:

http://spg.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=27299

In this drop, we have addressed a number of tasks:

  • Implemented trusted facade pattern and removed the fake SSO provider
  • Refactored the repositories to make better use of WCF Proxies
  • Support for UpdatePanel in SafeScriptManager
  • Updated PartnerLandingPage
  • Removed most usages of .net 3.5
  • Provided instructions on how to use a host name to access extranet site

Trusted facade pattern

We are demonstrating in our RI how to call back-end services from SharePoint. It’s quite common to have different credentials to log on to back end services.

Replacing the fake SSO provider

Before, we were using a fake SSO provider (Single Sign On) for that. We built a fake SSO provider because it’s actually quite hard and complex to build a real SSO provider. Since the SSO provider should store passwords in a secure way, there are a whole range of attacks you need to watch for. We felt we didn’t want to take on that extra complexity in our project, so we built a fake SSO provider that stored the passwords in clear text. We hoped that calling it ‘fake’ would make it clear enough that this is not something you would want to do in production.

We a lot of feedback that giving an example that shows how to store passwords in clear text is bad. No matter how clearly you explain that it’s not something you want to do in production, somebody is going to do it anyway. But since didn’t want to show you how to build a real SSO provider (that would be a project in itself), we decided to change our implementation to a trusted facade. 

Trusted facade explained

The following diagram shows the trusted facade pattern:

image

A user authenticates with the trusted facade. It validates the credentials provided by the user. Then, if the trusted facade calls the back end service on behalf of the user, it only specifies the username. The back end service trusts the Trusted Facade to provide the correct username, so it doesn’t need to perform any authentication.

We implemented our trusted facade based on this MSDN article. Our implementation looks like this:

image

A user connects to SharePoint either through windows authentication or through Forms Based Authentication (FBA). Then, when the user wants to make a request to a backend system, for example to retrieve the price for a product, the pricing repository will find out what partner the user belongs to. It will then call the back end service with the name of the partner. The pricing service trusts our SharePoint application to provide the correct partner name, so it doesn’t require any passwords. 

Of course, you have to make sure that only the account that SharePoint runs under is allowed to access the pricing service.

Repository refactoring

We took a critical look at our current implementation of the repositories.

The goal of the repositories is to hide data access logic from consumers. For example, we have a ProductCatalogRepository, which has methods like: GetProduct(string sku) to retrieve product information. This repository uses the BDC for some of it’s methods, but for other, it calls into our productcatalog webservices directly. However, the consumers of these repositories don’t know where the data comes from. They also don’t know (and don’t care) that the data is cached.

Webservice proxies

Adding a reference to a webservice is very simple in Visual Studio. What happens under the covers is quite a bit more complex. Visual studio will generate proxy classes based on the metadata that’s returned from the service.

We implemented the following best practices for calling web services:

  1. If your service references are used by multiple projects, create a single project that holds the service references and reference that project.
    There are to reasons for this. If you are making changes to your webservice, you only have to update one service reference. Forgetting to update one can cause annoying bugs. But from a design perspective, if you generate two proxies for the same web service, then you’ll have duplicate (incompatible) types in your system. For example, the price object generated for proxy 1 will be different from the price object generated for proxy 2. Even though they have exactly the same signature, you can’t reuse the types for them or reuse methods that work on them. We implemented this in the Contoso.Pss.Services.Client solution.
  2. Don’t call the service proxies directly, but wrap the calls to the service proxies into repositories or service agents.
    This best practice is used to shield your application from (minor) changes to the service. It does take some extra coding, because you have to transform the objects you get back from the service into objects that can be used by your application. So this practice does adds a level of indirection and extra complexity to your application, so you have to make the tradeoff if the extra complexity is worth the isolation. In general, if the services are created for and only used by your application, you typically don’t need such a level of indirection. However, if you don’t have control over your services or other clients are also using the services, it’s often worth it.

There were a couple of area’s we explicitly didn’t look at.

Getting the repositories from the service locator

Before, we were creating the repositories directly in our code, for example in our presenters. This is often undesirable, because it makes the presenters harder to unit test. Now, we have registered the repositories in our service locator. Therefore, we can use the service locator to get instances of our repositories and we are able to mock out these in our unit tests. Sweet :)

UpdatePanel in sharepoint

SharePoint has a slightly different method for implementing post backs than the normal ASP.Net framework. It uses a custom javascript method that is called on postback. Unfortunately, this means that the Ajax UpdatePanel doesn’t work out of the box, because it also requires a different postback method. The solution is to emit some JavaScript code that intercepts the postback event and calls the normal UpdatePanel posback code.

In order to get the UpdatePanel to work, you need a scriptmanager, because that will add the required javascript code for the async postback to the page. We had already built a SafeScriptManager, that you can add several times to a page without causing issues. So it was natural to add some functionality to it to enable support for the UpdatePanel.

 

Removed most .net 3.5 usages

We were making judicious use of the wonderful new features of .Net 3.5 such as Linq queries, lambda expressions and type initializers. However, we got the feedback from our advisors that .net 3.5 is not widely used by the sharepoint developer community. After many discussions, we agreed that removing most of the .net 3.5 usages would make our guidance a bit more consumable by the sharepoint developer community.

Added instructions on how to use a host name to access extranet site

Lastly, we added some instructions on how to use a host name to access extranet sites. Now, our extranet site is accessable on localhost:9001. If you would prefer to host the extranet site on a hostname, for example extranet.mydomain.com, we have included instructions on how to do that.

Hi guys,

Our drop 8 video is online on Channel 9. Check it out:

Happy watching and keep practicing!

_Erwin

A while ago, I put an example application on my blog on how to build an outlook style application.

The last couple of weeks, I’ve been working on a new version of this app. I’ve done some bugfixes, but also included support for opening use cases in a popup window. It’s turning out to be quite an advanced demo of what’s possible with Prism. But while I’m playing with it, I can’t help but be amazed with the things I can push Prism into doing :)

<Outlook style app>

You will need the following references to make the solution work:

So there are a couple of things I didn’t explain in my previous blog:

  • How to do ViewModel first development?
  • How to open a Use Case in a popup?
  • Why I’m using ObservableObject in my ViewModels?

So here goes:

ViewModel first development

I’m a big van of ViewModel first development. So what does that mean?

  1. I create my ViewModels before i create my Views. This allows me to create testable viewmodels that absolutely don’t rely on any visual aspects.
  2. My application code programs against ViewModels, not Views. Most of my code doesn’t need to know about the views. Only when a ViewModel needs to be displayed should you load up the view to display it.

There are a couple of big advantages to this approach:

  • You can easily unit test your UI logic, without relying on visual elements.
  • I can easily reskin my app.
  • You don’t have to forward data from your views to your view models. This is something I have always found annoying with a View First approach. For example, if you have a view that displays a person and needs a PersonID to do it. With view first, your code has to talk to the view. So the view needs a PersonID property. But actually, the logic of your view needs that PersonID, so it needs to be forwarded to your ViewModel. Annoying, tedious, error prone!!!

I wanted to be able to put ViewModels into my regions and to have some code that would provide the visualization onto it. So the code I want to be able to write is:

// 1: Setup visualizations (typically in Module.Initialize)
// Whenever an EmailMainViewModel is displayed, visualize it with an EmailMainView
modelVisualizationRegistry.Register<EmailMainViewModel, EmailMainView>();

// 2: Add ViewModels to region (view discovery, view injection or any other method)
region.Add(new EmailMainViewModel());

ViewModel First internals

If you’re interested in how I built the ViewModel First code? here it is:

ModelVisualizer

The first step into creating the view model first appraoch was to create a ModelVisualizer class. The reason for this was: "The prism region adapters will put the content of the regions directly into the control that hosts the region (for example, a contentcontrol). There is no extensionpoint to sit in between that.

So I created something that I could put in a region, that would hold BOTH the View and the ViewModel. It would be the glue between the view and the viewmodel and:

  • Set the View as the content in the Visual Tree.
  • Set the ViewModel as the datacontext for the View.
  • Forward common information between the ViewModel and the View (such as the RegionContext or the IsActive values)

The following diagram explains my ModelVisualizer.

image

The ModelVisualizer IS a ContentControl. So it can be placed inside the Visual Tree. It will set the View as the content. It will also set the ViewModel as the datacontext of the view (so the view can bind to all the information in the ViewModel). Lastly, the IModelVisualizer implements the IRegionContextAware and IActiveAware interfaces, and will synchronize these interfaces with the View and ViewModel if they implement the interfaces.

Visualizing Region

The ModelVisualizer worked great. However, it demanded that all my code knew about the ModelVisualizer. I didn’t want to do that, because I wanted to make it implicit. There were some issues with that though, because due to the current implementation the region adapters, I didn’t have an extension point to create my visualizations implicitly. I couldn’t change the type of region that was created by adapters and I couldn’t change how the adapters set the content of the region to the hostcontrol. But I solved that with a little trick, that I call my VisualizingRegion.

The trick was: while I couldn’t change what type of region was being created, I could control what type of region was registered to the RegionManager (because there is a regionbehavior that does the registration. So I just wrapped the Region that was created by the regionadapters in my own region (the visualizing region) and registered my own visualizing region to the regionmanager.

The only way a consumer can get access to the Region is through the RegionManager, so that solved the problem :)

Easier Solution to region context

In Prism V2, we introduced the concept of RegionContext. The RegionContext is a way that a view that hosts a region can share some of it’s information with any childviews that are loaded into it’s region. While I really liked the concept of RegionContext, I didn’t really like the implementation of it.

So I created the IRegionContextAware interface. It has one property (the regioncontext as an ObservableObject) and the RegionContextAwareRegionBehavior that would sync the context of the region with the RegionContextAware properties.

Opening a Use Case (or ViewModel) in a popup

One thing I thought was an interesting challenge was opening a viewmodel in a (non modal) popup. So why would this be challenging:

  • You can have many instances of the same popup open at the same time.
  • Viewmodels shouldn’t know if they are opened in the main window (perhaps in several tabs) or in a popup. This should be decided by the designer, preferably in XAML.

The code I wanted to be able to write is:

   1: // Create an UseCase to write new email messages
   2: NewEmailUseCase newEmailUseCase = ApplicationModel.CreateObjectInScopedRegionManager<NewEmailUseCase>();
   3:  
   4: // Add some data to the Email message use case (in this case, a blank new email)
   5: newEmailUseCase.Message = new EmailMessage();
   6:  
   7: // Show the email (in a popup, but the consumer doesn't know that)
   8: ApplicationModel.ShowUseCase(newEmailUseCase);

The problem with opening several instances of the same popup is: Regions are identified by name in the regionmanager. If you have several popups of the same type open, each popup needs it’s own RegionManager, or else the region names will collide.  In my scenario, I decided that the Popup has most of the same region names as the main shell. That way, any ViewModel or use case could be loaded in either the popup or the main window.

Creating use cases in a scoped regionmanager

Ok, so i need to create a scoped regionmanager. That’s not to hard, just do: RegionManager.CreateRegionManager() and you have one. However, I wanted the consuming code NOT to have to think about this. It should be blissfully ignorant about the fact that it’s in a scoped regionmanager or not.

Since all most of my objects are created by a DI Container, and it injects all of the dependencies to my object, I decided to use that to solve this problem. So I created a scoped Container and registered the scoped regionmanager with that. Then I created my use case from the newly created scoped container, and if it needs a regionmanager, it would automatically get the scoped regionmanager. Pretty neat huh.

So schematic, that looks like this:

image

So when the use case (in green) get’s created, it and it’s dependencies would get the scoped regionmanager injected. Without knowing about the scoped containers or scoped regionmanager.

Adding use cases to popups

Adding the use case to a popup (in the application model) works like this:

image

  1. Create the use case.
    Your code creates a new use case instance, for example new NewEmailUseCase(); The application model has a method to create a use case within a new RegionManager scope (as described before).
  2. Show use case.
    Your code calls the Application model to show the use case.
  3. Add to region.
    The application model (which is logic) doesn’t even know if the use case is displayed in a popup or not. It just adds the use case to a region. The region itself is defined in the Shell.XAML.
  4. Visualize the Use case
    Just as a visualization (view) can be registered for ViewModels, i’ve also registered a visualization for Use Cases. In this case, I’ve registered a window (called Popup.XAML) as visualization.
  5. Show /Close the popup on activate.
    Now that the visualization is there, I had to create some code to show and close the popup. I decided that, if i Activate() the use case, the popup should be displayed. If I deactivate Use case, the popup should be closed and the use case should be removed from the region. This functionality I put in a RegionBehavior, because it can easily monitor if something is added or removed from a region.
  6. Assign scoped region manager to the popup
    Lastly, the popup window needs to know the RegionManager that the Use Case wants to use. So I’ve created the IRegionManagerAware interface. If a usecase implements that interface, anything that’s placed inside the region will get this region manager assigned.

As you can see, there are quite a lot of moving bits for showing a use case into a popup. Of course, it would have been A LOT easier to give ‘your code’ (an other use case or something) the knowledge that a view can be opened in popup. 

ObservableObject for easier binding

If you look at my viewmodels, you’ll see that I make use of the ObservableObject a LOT. It’s a very simple object, one that just takes a type and wraps it in a INotifyPropertyChanged. The nice thing about this is, that I don’t have to add any INotifyPropertyChanged code in my ViewModels anymore. That makes it soooo much easier to do 2 way databinding in WPF.

The only problem is, that to get to the value, you often have to do: viewModel.MyProperty.Value to get to the actual value of MyProperty. But I thought that’s worth it since now I don’t have to write INotifyPropertyChanged code for my properties anymore.

 

 

Conclusion

Like I mentioned, before, this outlook style app has become quite an advanced demo of what’s possible with Prism. But I hope it gives you some idea’s on what’s possible with it. I’m also in the process of creating a video walkthrough of this application. But I’ll let you know when that’s done!

Keep practicing!

_Erwin

[UPDATE]

If you get an System.Threading.SynchronizationLockException from Unity: Don’t worry! I had turned on ‘break on all exceptions’ so the debugger is also breaking on these handled exceptions. Just continue and the app will run fine, or change that debug setting.

Last Friday, we’ve released drop 8 of our Guidance.

 

What did we tackle in iteration 8

The main theme in drop 8 was exception handling in SharePoint. But we also did a bunch of refactoring in the application:

  • Service locator
    We want to create a true service locator for sharepoint. However, this is a bit lower on our priority list. So for now we have the interface in place and will keep refactoring it in future drops.
  • Ajax support feature
    We already had an feature that allowed you to add Ajax support to your page. We’ve now cleaned up the code a bit more.
  • LOB Services support
    Created LOB Service Support project to deploy web.config modifications required for LOB services

Exception handling

We looked at a bunch of exception handling scenario’s and how they relate to SharePoint.

The general guidance around exception handling still applies to programming in SharePoint. For example:

  • Use exceptions for exceptional situations. Avoid using error codes to signify error conditions.
  • Use specific exception types. Avoid throwing and catching Exception directly like the plague.
  • Only catch exceptions that you can handle.
  • Never ever EVER EVER catch(Exception ex) and swallow it! This can result in bugs that are almost impossible to find! The ONLY place where you can do this, is in an unhandled exception handler where you should:
    • Log the exception
    • Show the user a friendly message: “We’re so sorry, but something went wrong. Please try again later.” or something.
    • Let the application die gracefully.

But please do read the general guidance with regards to exception handling. It’s a good read :)

 

Exception handling in SharePoint

It’s common to have different exception handling strategies for different places in your application. For example, in your web services, you’ll typically apply exception shielding, where you would log the original exception and replace it with a generic error message. An other example would be in your UI, where you would want to log the exception and display a message to a user.

We looked at a couple of these strategies for exceptionhandling in SharePoint where we can apply additional guidance or help. We’ve looked at exception handling in:

  • Pages
    Exception handling in pages in sharepoint is not very different from exception handling in normal ASP.Net, so there is not that much we can provide Sharepoint specific guidance on.
  • Webparts and usercontrols
    Technically, exception handling in webparts and usercontrols in SharePoint is not very differnet from exception handling in asp.net. However, since end-users can create their own pages by dragging several webparts on a page, you often don’t want a single webpart to take down the whole page. So we’ve built an Exception Handling stragety for webparts.
  • ListItemEventReceiver
    If an unhandled exception occurs in a ListItemEventReceiver, what you typically want to do is cancel the action and set the error message. However, if you forget to cancel the action, the change will still continue, which can cause all sorts of problems.  So we’ve built an exception handling stragety for ListItemEventReceivers.
  • Workflows
    It’s pretty easy to implement exception handling in workflows, so we haven’t built anything for it. We’ll probably add some guidelines in our guidance though.

Exceptionhandling in webparts and usercontrols

The default behavior of an unhandled exception in a web part is that the exception will bubble up to the page. There asp.net will redirect to an error page. Since SharePoint allows you to dynamically create pages and add some webparts to them, you might not want a single webpart to take down the whole page. So we’ve built something to allow you to do just that.

We typically apply the Model – View – Presenter pattern to webpart development, because that allows us to easily unit test our UI logic. This pattern looks like this:

image

The webpart loads up a view (an UserControl, to allow for the design time experience). The View loads up a presenter that holds all the UI logic and only communicates to the presenter using a interface (so we can mock out the view during while testing).

So how would we create an exceptionhandler for the webparts that can show error messages? The easiest approach is to allow the view to render error messages:

image

So our Presenter uses an ExceptionHandler to log and show exception messages. However, the (generic) Exceptionhandler needs some mechanism to display error messages. In this case, our view is the only thing our presenter knows. So we gave the view a special interface, the IErrorVisualizer interface, that the ExceptionHandler can use to display the correct error mesage.

You might not want to make the view responsible for showing 'fatal’ error messages. For one reason, makes the view more complicated. Another reason might be, that you would want a consistent way of displaying error messages across all your webparts. In that case, the following pattern might be better:

image

In this case, we’ve created an error visualizer. It’s just a control that knows how to display error messages. It implements the IErrorVisualizer interface. This way, the view is blissfully unaware on how errors are being displayed.

Now, if the presenter wants to call the error message, it not only needs a reference to the IMyView, but also to the IErrorVisualizer.

This is what the code from the presenter looks like:

   1: public void LoadProduct(string sku)
   2: {
   3:     try
   4:     {
   5:         logger.LogDiagnostic("In OnViewLoaded.");
   6:  
   7:         Product product = productCatalogRepository.GetProductBySku(sku);
   8:  
   9:         if (product == null || product.Sku == null)
  10:         {
  11:             // Show an error message to the user
  12:             new ViewExceptionHandler().ShowFunctionalErrorMessage("Could not find product information.", this.ErrorVisualizer);
  13:         }
  14:         else
  15:         {
  16:             this.view.Product = product;
  17:             this.view.DataBind();
  18:         }
  19:     }
  20:     catch(Exception ex)
  21:     {
  22:         // If something goes wrong, make sure the error gets logged
  23:         // and a non technical message is displayed to the user
  24:         new ViewExceptionHandler().HandleViewException(ex, this.ErrorVisualizer, 
  25:             "Due to a technical problem, the product details cannot be displayed.");
  26:     }
  27: }

All the code from the presenter is now in a try catch block. In the catch, we call the ViewExceptionHandler to handle the error. In this case, handling the error means: Log the error and show a ‘friendly’ error message.


Exceptionhandling in ListEventReceiver

Another ExceptionHandling strategy we’ve created is the ListExceptionhandler strategy.

If an unhandled exception occurs in a list, you should take the following actions:

  • Log the Exception
  • Set the ErrorMessage
  • Consider if you should cancel the action. We feel that de default action should be cancel, to avoid any potential harmful entries from entering your list.

So we’ve built a ListItemExceptionhandler that will do that for you.

Conclusion

As always, we hope you like the stuff we’re showing. If you have any feedback, comments or questions, feel free to ask me or the team (through the codeplex forums).

More Posts Next page »
 
Page view tracker