Tag Archives: ViewModel

Combining Silverlight Navigation Framework and Prism to create MVVM Applications – Introduction

This is introductory post for a series of posts where i will try to tackle the holy grail of MVVM applications – Navigation.

To do this I will be using Prism from Microsoft’s Patterns and Practices team (Silverlight version – latest drop) combined with Silverlight Navigation Framework and i will build small navigation framework on top of that.

If you are too busy to read this post and just want to see the result take a look at the current state of the sample Silverlight Prism Navigation application where you can see most of the important features of this small navigation framework (PrismExtensions.dll that contains all the framework code is 35.5 KB in size).

And for those of you with stronger nerves here is the real story:

Lately i have been playing with my old friend Prism and re-discovering how good it is for building MVVM Silverlight and WPF applications.

Out of the box you get a lot of things (and only few months ago i was trying to build all of this from scratch – you can see that from my earlier MVVM blog posts).

One of the things i like the most in Prism is the modularity concept and support for loading application modules dynamically from local/remote servers – on users/application request.

This allows developers to cut the application in modules with isolated functionality and on start load only mandatory parts and then load other modules only if users really needs/request them.

What really surprised me is that nobody has so far managed to combine Prism with Silverlight’s excellent Navigation Framework in a successful way so that is usable for real-life MVVM applications (at least i could not find any good examples on the web).

Prism has a concept of Regions and allows easy loading of Views into them but this is where it ends – there are no higher level concepts of navigation – this is why i decided to build some kind of Navigation framework on top of Prism – to fill that gap.

This is where the very important concept of Deep Linking comes into the story. I cannot imagine any serious Silverlight application without allowing users to bookmark pages in the browser, and to use the Back and Forward browser button to navigate though the UI, to manually ‘hack’ the URLs to load different data etc…

So this is something where Silverlight Navigation Framework can help us. It has built in support for all major browsers for browser history, it notifies the application about the browser URL change, there is HyperlinkButton control that has NavigateUri property where you can specify the application URL that will be loaded when user clicks on it (without full page reload off course – because only the fragment of the URL after # sign is changed) etc.

The only problem is that there is no easy way to combine Prism and Silverlight Navigation Framework.

Yes we can implement INavigationContentLoader and plug it into the Frame control but still we don’t have full control over the page/view loading process, we need additional Frame for each Region where we want to show Views etc.

So i decided to do a little research on how to simplify things and to create a small framework for Prism that will use Silverlight Navigation Framework to load Views into Prism Regions and enable Deep Linking, passing parameters to views, to allow integration with Prism modularity and allow deferred module loading etc – in other words all the features that one would expect to have in modern RIA Silverlight application.

Here are some features that i already support or will in near future:

  • it must be a simple (for the end user-developer) but full blown Navigation Framework for Prism Silverlight MVVM applications
  • it will support this main MVVM scenario: application will have one Main View (so called ‘Shell’) that will be loaded on start of the application and this will be the main ‘screen’ of the application that will have multiple regions where we can load Views. Only one region will be considered as Main Region and it will be ‘tied’ to the URL typed in the browser. Other regions will not update browsers URL or be affected by changes in the URL but application will be able to load Views into other regions – for example Widgets etc (i decided not to support Regions inside Views loaded into Regions on Main Region as this greatly simplifies the implementation and i don’t see a real usage scenario anyway –  instead of using Sub-Regions you can always use child Views inside of your View for that).
  • support for passing the parameters to the Views via browsers URL – every update in the URL of the browser will load appropriate view in Main Region (and pass parameters from URL to the Views ViewModel) and on the other hand, if some View is loaded to Main Region from code, this will reflect on the browser URL (including the parameters passed to View).
  • when View is loaded into region it will be connected to its ViewModel (set as its DataContext) – this is done automagically by the framework, user just needs to define the mapping between Views and View Models in the Module initialization – more details on that in later posts.
  • support for manually loading Views from ViewModels via code (not only via URLs) using the same framework – via some service like IPrismViewLoadingService
  • framework should include support for Prism deferred loading of application Modules – there should be easy way to load Prism Modules that are marked as OnDemand and they should be loaded either manually – from code or automagically – when user navigates to URL that should show View that is in module marked as ‘OnDemand’
  • there should be a way to define User Friendly URL’s – aliases for specific Views and Modules but some smart defaults should work out of the box by default like: “/Products/Detail/1234″  or “/ProductsModule/Details/1234″ etc – user should just type the URL in browser and Framework must load the Module if needed and then show the View (bound to its initialized ViewModel)
  • full support for navigation between Views using HyperlinkButton controls – for loading Views to Main Region and to other Regions
  • framework should be ‘opinionated’ regarding the way how it initializes and binds Views and their ViewModels – in our case it will be View-ViewModel-Marriage approach: there is separate service that initializes ViewModel and set it as DataContext of the View.
  • it should be simple to use for the end user-developer – smart defaults should work without any user configuration yet customization should be possible for advanced scenarios
  • whole solution should be based on services that implement defined interfaces – so that they can be easily changed with different implementations that user could plug via IOC – for example to easily change the parameters format from ‘parameterA/value1/parameterB/value2′ into ‘?parameterA=value1&parameterB/value2′ etc.

So this features should be enough to get us started but we can change this along the way if we see that its appropriate – if you have some suggestions – do let me know!

As you can see from the Sample Application I already have implemented most of these features and I will be finishing along the way as i write more posts in the future – what you can see in the demo right now is: Browser URL history integration (Deep Linking and Back/Forward buttons support), Loading Views with their corresponding ViewModels to Main Region and to secondary Regions, passing parameters to Views, asynchronous deferred loading of Modules/Views etc.

If some you know of some other Prism Navigation Framework that already has most of these features please let me know so i can stop doing this and enjoy real life :)

Otherwise see ya soon in the next part of this article series where i will explain all about this framework and share some code with usage scenarios.

Unit Testing Modal Dialogs in MVVM and Silverlight 4

As feedback to my recent post on Modal Dialogs in MVVM and Silverlight 4 I have received comments that the solution is not easy to Unit Test so i decided to create small blog posts on this subject just to show how simple and clean it is to do this.

So for those who are too lazy to read my original modal dialog post here is a quick reminder:

  • I presented a simple solution how to abstract modal dialogs and message boxes in Silverlight 4 and call them from your ViewModel and act according to the results returned from those modal dialogs.
  • I used Silverlight’s ChildWindow control because it was perfect fit for that job.
  • Important thing is to say that ChildWindow control was used as implementation (with its ViewModel off course) but was hidden by abstractions (like IModalWindow and IModalWindowService) so it can easily be changed by some other implementation and unit tested, mocked out etc.

So in this post i will use the same simple Demo Application for the previous modal dialogs post but I will add few Unit Tests using Silverlight Unit Testing Framework and Silverlight verstion of RhinoMocks.

Our Sample app is very simple and just shows a view with list of some User entities.

Each of users can be edited by clicking on EDIT button next to them – this shows a modal dialog with User editor, we can change details and save them by clicking on OK or CANCEL.

Also there is option to delete each User by clicking on the DEL button – Message Box is shown with OK/Cancel buttons – these are very common scenarios for every LOB application so that’s why i picked them.

I must admit that i improved my framework since the previous post – I changed the signature of the IModalDialogService a little because now in my framework i have a IViewInitializationService that wires up ViewModels with Views so all this is used in this posts just to show it off :)  (more on the IViewInitializationService and the new way how i wire up ViewModels and View in one of the next posts).

So first let’s see the changes made to the IModalDialogView that is the abstraction of the actual modal dialog to be shown:

  public interface IModalWindowView : IView
  {
    bool? DialogResult { get; set; }
    event EventHandler Closed;
    void Show();
    void Close();
  }

So the real ChildWindow that will be our dialog only needs to be marked as implementor of IModalWindowView interface with no additional code needed since this interface contains only methods and properties that ChildWindow already implements:

    public partial class EditUserModalDialogView : IModalWindowView
    {
        public EditUserModalDialogView()
        {
            InitializeComponent();
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }
    }

Also you could see that our IModalDialogView implements our old friend – IView:

    public interface IView
    {
        object FindName(string name);
        object DataContext { get; set; }
        string Name { get; set; }
        event RoutedEventHandler Loaded;
    }

Again nothing to implement here – no code to add – because ChildWindow already implements all this since its inheriting the ContentContol that has all this.

So now lets see the MainPageViewModel for our MainPageView that will actually show the modal dialogs and message boxes:

    public class MainPageViewModel : ViewModel
    {
        private readonly IModalDialogService modalDialogService;
        private readonly IMessageBoxService messageBoxService;
        private ObservableCollection<User> users = new ObservableCollection<User>();

        public MainPageViewModel(IModalDialogService modalDialogService, IMessageBoxService messageBoxService)
        {
          this.modalDialogService = modalDialogService;
          this.messageBoxService = messageBoxService;

          this.Users = new ObservableCollection<User>();

          for (int i = 1; i < 6; i++ )
          {
            this.Users.Add(new User {Username = string.Format("Admin User {0}",
                new Random((int)DateTime.Now.Ticks).Next(10,100)), IsAdmin = true});
            Thread.Sleep(100);
          }

          this.ShowUserCommand =
              new DelegateCommand<User>(userInstanceToEdit =>
                                      {
                                       this.modalDialogService.ShowDialog<EditUserModalDialogViewModel>
                                             (
                                             userInstanceToEdit,
                                             (dialog, returnedViewModelInstance) =>
                                             {
                                                if (dialog.DialogResult.HasValue && dialog.DialogResult.Value)
                                                {
                                                var oldItem = this.Users.FirstOrDefault( u => u.Id == userInstanceToEdit.Id);
                                                var oldPos = this.Users.IndexOf(oldItem);
                                                if (oldPos > -1)
                                                {
                                                    this.Users.RemoveAt(oldPos);
                                                    this.Users.Insert(oldPos, returnedViewModelInstance.User);
                                                }
                                                }
                                            });
                                       });

          this.DeleteUserCommand = new DelegateCommand<User>
              (p =>
                                    {
                                        var result = this.messageBoxService.Show(string.Format(
                                            "Are you sure you want to delete user {0} ???", p.Username),
                                            "Please Confirm", GenericMessageBoxButton.OkCancel);
                                        if (result == GenericMessageBoxResult.Ok)
                                        {
                                        this.Users.Remove(p);
                                        }});

        }

        public ObservableCollection<User> Users
        {
            get { return users; }
            set { users = value;
            this.OnPropertyChanged("Users");
            }
        }

        private ICommand showUserCommand;
        public ICommand ShowUserCommand
        {
            get { return showUserCommand; }
            set { showUserCommand = value;
                this.OnPropertyChanged("ShowUserCommand");
            }
        }

      private ICommand deleteUserCommand;
      public ICommand DeleteUserCommand
      {
        get { return deleteUserCommand; }
        set { deleteUserCommand = value;
        this.OnPropertyChanged("DeleteUserCommand");
        }
      }
    }

As you see ViewModel is simple class and it just has a list of Users to be shown by its View and important things to notice here are two commands for editing and deleting single user.

ShowUserCommand shows modal dialog for editing single user, and DeleteUserCommand just shows MessageBox for confirmation of deletion with OK and Cancel buttons.

So now comes the fun part, lets write unit tests for those commands:

First UnitTest checks that our ShowUserCommand shows the modal dialog for editing the user (using the IModalDialogService). We put expectation on our IModalDialogService mock and invoke our command on ViewModel and verify all expectations afterwards.

Here is the code:

        [TestMethod]
        public void ShowUserCommand_WhenCalledWithSpecificUser_ShowsModalDialogByPassingThatUserAsInitParam()
        {
            var viewModel = GetInitializedAndMockedViewModel();

            viewModel.Users = GenerateSampleUsers();

            var userToSend = viewModel.Users[1];

            modalDialogService.Expect(
                p => p.ShowDialog<EditUserModalDialogViewModel>(null, null))
                .Constraints(
                Is.Same(userToSend),
                Is.TypeOf(typeof(Action<IModalWindowView, EditUserModalDialogViewModel>)))
                .Repeat.Once();

            viewModel.ShowUserCommand.Execute(userToSend);

            modalDialogService.VerifyAllExpectations();
        }

We first get our ViewModel with Rhino-mocked instances of IModalDialogService and IMessageBoxService and some test Users by calling this methods:

        private static ObservableCollection<User> GenerateSampleUsers()
        {
            return new ObservableCollection<User>()
                                  {
                                      new User() {Username = "user 1"},
                                      new User() {Username = "user 2"},
                                      new User() {Username = "user 3"}
                                  };
        }

        private MainPageViewModel GetInitializedAndMockedViewModel()
        {
            this.modalDialogService = MockRepository.GenerateMock<IModalDialogService>();
            this.messageBoxService = MockRepository.GenerateMock<IMessageBoxService>();
            return new MainPageViewModel(this.modalDialogService, this.messageBoxService);
        }

So that was easy or what?

Lets go to next Unit Test. Lets check that when we call ShowUserCommand with instance of User that when it shows dialog and dialog returns true as its DialogResult – that we replace the original User in ViewModel’s list of Users with the one we got from the modal dialog:

        [TestMethod]
        public void ShowUserCommand_WhenCalledWithSpecificUserAndOnModalDialogResultIsTrue_ShouldReplaceTheOriginalUserInstanceWithOneReturnedFromModel()
        {
            var viewModel = GetInitializedAndMockedViewModel();

            viewModel.Users = GenerateSampleUsers();

            var userToSend = viewModel.Users[1];

            var dialog = MockRepository.GenerateMock<IModalWindowView>();
            dialog.Expect(p => p.DialogResult).Return(true);

            var mockViewModel = MockRepository.GenerateStub<EditUserModalDialogViewModel>();
            mockViewModel.User = new User() {Username = "mocked"};

            modalDialogService.Expect(
                p => p.ShowDialog<EditUserModalDialogViewModel>(null, null))
                .Constraints(
                    Is.Same(userToSend),
                    Is.TypeOf(typeof (Action<IModalWindowView, EditUserModalDialogViewModel>)))
                .Repeat.Once().WhenCalled(
                    m =>
                        {
                            var action = (m.Arguments[1] as Action<IModalWindowView, EditUserModalDialogViewModel>);
                            if (action != null)
                            {
                                action.Invoke(dialog, mockViewModel);
                            }
                        });

            viewModel.ShowUserCommand.Execute(userToSend);

            Assert.AreEqual("mocked", viewModel.Users[1].Username);
        }

And here is the unit test that checks the DeleteUserCommand so that it actually deletes the user from the ViewModel’s list of users if OK button was clicked on the shown message box:

        [TestMethod]
        public void DeleteUserCommand_WhenCalledWithSpecificUserAndCallToMessageBoxServiceReturnsOk_ShouldDeleteThatUser()
        {
            // arrange
            var viewModel = GetInitializedAndMockedViewModel();

            viewModel.Users = GenerateSampleUsers();

            var userToSend = viewModel.Users[1];

            this.messageBoxService.Expect(p => p.Show(null, null, GenericMessageBoxButton.OkCancel)).Constraints(
                Is.Anything(), Is.Anything(),
                Is.Anything()).Return(GenericMessageBoxResult.Ok);

            // act
            viewModel.DeleteUserCommand.Execute(userToSend);

            // assert user is not there anymore
            Assert.IsFalse(viewModel.Users.Any( u => u.Username == userToSend.Username));
        }

So it turned out that its quite simple to test Modal Dialogs as long as you have the proper abstractions in place ;)
You can open this page to see all the unit tests running in browser.

Those tests are actually running on the code from the sample demo app!

And as you see all the Unit Tests are green, and the world is safe again :D

Here is the code for all the tests, that is – all 9 of them:

namespace UnitTestingModalDialogs.Tests
{
    [TestClass]
    public class MainPageViewModelTests
    {
        private IModalDialogService modalDialogService;
        private IMessageBoxService messageBoxService;

        private static ObservableCollection<User> GenerateSampleUsers()
        {
            return new ObservableCollection<User>()
                                  {
                                      new User() {Username = "user 1"},
                                      new User() {Username = "user 2"},
                                      new User() {Username = "user 3"}
                                  };
        }

        private MainPageViewModel GetInitializedAndMockedViewModel()
        {
            this.modalDialogService = MockRepository.GenerateMock<IModalDialogService>();
            this.messageBoxService = MockRepository.GenerateMock<IMessageBoxService>();
            return new MainPageViewModel(this.modalDialogService, this.messageBoxService);
        }

        [TestMethod]
        public void ShowUserCommand_WhenCalledWithSpecificUser_ShowsModalDialogByPassingThatUserAsInitParam()
        {
            var viewModel = GetInitializedAndMockedViewModel();

            viewModel.Users = GenerateSampleUsers();

            var userToSend = viewModel.Users[1];

            modalDialogService.Expect(
                p => p.ShowDialog<EditUserModalDialogViewModel>(null, null))
                .Constraints(
                Is.Same(userToSend),
                Is.TypeOf(typeof(Action<IModalWindowView, EditUserModalDialogViewModel>)))
                .Repeat.Once();

            viewModel.ShowUserCommand.Execute(userToSend);

            modalDialogService.VerifyAllExpectations();
        }

        [TestMethod]
        public void ShowUserCommand_WhenCalledWithSpecificUserAndOnModalDialogResultIsTrue_ShouldReplaceTheOriginalUserInstanceWithOneReturnedFromModel()
        {
            var viewModel = GetInitializedAndMockedViewModel();

            viewModel.Users = GenerateSampleUsers();

            var userToSend = viewModel.Users[1];

            var dialog = MockRepository.GenerateMock<IModalWindowView>();
            dialog.Expect(p => p.DialogResult).Return(true);

            var mockViewModel = MockRepository.GenerateStub<EditUserModalDialogViewModel>();
            mockViewModel.User = new User() {Username = "mocked"};

            modalDialogService.Expect(
                p => p.ShowDialog<EditUserModalDialogViewModel>(null, null))
                .Constraints(
                    Is.Same(userToSend),
                    Is.TypeOf(typeof (Action<IModalWindowView, EditUserModalDialogViewModel>)))
                .Repeat.Once().WhenCalled(
                    m =>
                        {
                            var action = (m.Arguments[1] as Action<IModalWindowView, EditUserModalDialogViewModel>);
                            if (action != null)
                            {
                                action.Invoke(dialog, mockViewModel);
                            }
                        });

            viewModel.ShowUserCommand.Execute(userToSend);

            Assert.AreEqual("mocked", viewModel.Users[1].Username);
        }

        [TestMethod]
        public void ShowUserCommand_WhenCalledWithSpecificUserAndOnModalDialogResultIsFalse_ShouldNotReplaceTheItemInViewModelWithOneReceivedFromDialog()
        {
            var viewModel = GetInitializedAndMockedViewModel();

            viewModel.Users = GenerateSampleUsers();

            var userToSend = viewModel.Users[1];

            var dialog = MockRepository.GenerateMock<IModalWindowView>();
            dialog.Expect(p => p.DialogResult).Return(false);

            var mockViewModel = MockRepository.GenerateStub<EditUserModalDialogViewModel>();
            mockViewModel.User = new User() { Username = "mocked" };

            modalDialogService.Expect(
                p => p.ShowDialog<EditUserModalDialogViewModel>(null, null))
                .Constraints(
                    Is.Same(userToSend),
                    Is.TypeOf(typeof(Action<IModalWindowView, EditUserModalDialogViewModel>)))
                .Repeat.Once().WhenCalled(
                    m =>
                    {
                        var action = (m.Arguments[1] as Action<IModalWindowView, EditUserModalDialogViewModel>);
                        if (action != null)
                        {
                            action.Invoke(dialog, mockViewModel);
                        }
                    });

            viewModel.ShowUserCommand.Execute(userToSend);

            Assert.AreNotEqual("mocked", viewModel.Users[1].Username);
        }

        [TestMethod]
        public void ShowUserCommand_WhenCalledWithSpecificUserAndOnModalDialogResultIsNull_ShouldNotReplaceTheItemInViewModelWithOneReceivedFromDialog()
        {
            var viewModel = GetInitializedAndMockedViewModel();

            viewModel.Users = GenerateSampleUsers();

            var userToSend = viewModel.Users[1];

            var dialog = MockRepository.GenerateMock<IModalWindowView>();
            dialog.Expect(p => p.DialogResult).Return(null);

            var mockViewModel = MockRepository.GenerateStub<EditUserModalDialogViewModel>();
            mockViewModel.User = new User() { Username = "mocked" };

            modalDialogService.Expect(
                p => p.ShowDialog<EditUserModalDialogViewModel>(null, null))
                .Constraints(
                    Is.Same(userToSend),
                    Is.TypeOf(typeof(Action<IModalWindowView, EditUserModalDialogViewModel>)))
                .Repeat.Once().WhenCalled(
                    m =>
                    {
                        var action = (m.Arguments[1] as Action<IModalWindowView, EditUserModalDialogViewModel>);
                        if (action != null)
                        {
                            action.Invoke(dialog, mockViewModel);
                        }
                    });

            viewModel.ShowUserCommand.Execute(userToSend);

            Assert.AreNotEqual("mocked", viewModel.Users[1].Username);
        }

        [TestMethod]
        public void DeleteUserCommand_WhenCalledWithSpecificUser_ShouldCallMessageBoxServiceWithSomeTextThatContainsThatUsersUsername()
        {

            // arrange
            var viewModel = GetInitializedAndMockedViewModel();

            viewModel.Users = GenerateSampleUsers();

            var userToSend = viewModel.Users[1];

            this.messageBoxService.Expect(p => p.Show(null, null, GenericMessageBoxButton.OkCancel)).Constraints(
                Is.Matching<string>(txt => txt.Contains(userToSend.Username)), Is.Anything(),
                Is.Equal(GenericMessageBoxButton.OkCancel)).Return(GenericMessageBoxResult.Ok);

            // act
            viewModel.DeleteUserCommand.Execute(userToSend);

            // assert
            this.messageBoxService.VerifyAllExpectations();
        }

        [TestMethod]
        public void DeleteUserCommand_WhenCalledWithSpecificUser_ShouldCallMessageBoxServiceWithOkCancelParamForButtons()
        {

            // arrange
            var viewModel = GetInitializedAndMockedViewModel();

            viewModel.Users = GenerateSampleUsers();

            var userToSend = viewModel.Users[1];

            this.messageBoxService.Expect(p => p.Show(null, null, GenericMessageBoxButton.OkCancel)).Constraints(
                Is.Anything(), Is.Anything(),
                Is.Equal(GenericMessageBoxButton.OkCancel)).Return(GenericMessageBoxResult.Ok);

            // act
            viewModel.DeleteUserCommand.Execute(userToSend);

            // assert
            this.messageBoxService.VerifyAllExpectations();
        }

        [TestMethod]
        public void DeleteUserCommand_WhenCalledWithSpecificUserAndCallToMessageBoxServiceReturnsOk_ShouldDeleteThatUser()
        {
            // arrange
            var viewModel = GetInitializedAndMockedViewModel();

            viewModel.Users = GenerateSampleUsers();

            var userToSend = viewModel.Users[1];

            this.messageBoxService.Expect(p => p.Show(null, null, GenericMessageBoxButton.OkCancel)).Constraints(
                Is.Anything(), Is.Anything(),
                Is.Anything()).Return(GenericMessageBoxResult.Ok);

            // act
            viewModel.DeleteUserCommand.Execute(userToSend);

            // assert user is not there anymore
            Assert.IsFalse(viewModel.Users.Any( u => u.Username == userToSend.Username));
        }

        [TestMethod]
        public void DeleteUserCommand_WhenCalledWithSpecificUserAndCallToMessageBoxServiceReturnsCancel_ShouldNOTDeleteThatUser()
        {
            // arrange
            var viewModel = GetInitializedAndMockedViewModel();

            viewModel.Users = GenerateSampleUsers();

            var userToSend = viewModel.Users[1];

            this.messageBoxService.Expect(p => p.Show(null, null, GenericMessageBoxButton.OkCancel)).Constraints(
                Is.Anything(), Is.Anything(),
                Is.Anything()).Return(GenericMessageBoxResult.Cancel);

            // act
            viewModel.DeleteUserCommand.Execute(userToSend);

            // assert user is not there anymore
            Assert.IsTrue(viewModel.Users.Any(u => u.Username == userToSend.Username));
        }

        [TestMethod]
        public void DeleteUserCommand_WhenCalledWithSpecificUserAndCallToMessageBoxServiceReturnsCancel_ShouldNOTDeleteAnyUser()
        {
            // arrange
            var viewModel = GetInitializedAndMockedViewModel();

            viewModel.Users = GenerateSampleUsers();

            var userToSend = viewModel.Users[1];

            this.messageBoxService.Expect(p => p.Show(null, null, GenericMessageBoxButton.OkCancel)).Constraints(
                Is.Anything(), Is.Anything(),
                Is.Anything()).Return(GenericMessageBoxResult.Cancel);

            var usersCountBefore = viewModel.Users.Count;
            // act
            viewModel.DeleteUserCommand.Execute(userToSend);

            // assert user is not there anymore
            Assert.AreEqual(usersCountBefore, viewModel.Users.Count);
        }

    }
}

If you want to investigate further download the Visual Studio 2010 solution and play with it – feel free to use the code as you wish and remember to have fun!

Unit Testable WCF Web Services in MVVM and Silverlight 4

In all my previous MVVM in Silverlight 4 posts i was avoiding to address one painful aspect of the Silverlight: calling WCF Web Services.

And it was not without reason. Lets face it, consuming WCF Web Services from your Silverlight application can be pretty hard.

I mean hard to do it in a clean way off course.

Yes we all know how to create a Silverlight enabled WCF Web Service from Visual Studio but things become messy from that point.

First question is how to invoke methods of the web service?

Should we use Add Web Service Reference from the Visual Studio and and get the service proxy generated for us by the IDE?

If you go down that route, its easy to start and you will be invoking web service methods asynchronously in no time, but you will pay the price for that simplicity later, that is for sure.

Next problem is how to Unit Test those web service calls – its impossible to abstract the generated proxy in a clean way.

Then if you change your Web Service signature, you have to rebuild your Proxy. This can be troublesome especially if more than one person is working on the same project (can be avoided using build scripts to rebuild proxy automatically during compilation but still i don’t like that).

Also invoking web service methods asynchronously is tedious work in terms of writing the same code over and over again.

You have to subscribe to the OnCompleted event, and then invoke the actual asynchronous method, and then when your OnComplete handler is invoked, you can process the results of the web service method.

Not to mention the lifetime of the generated proxy, and handling exceptions that could be thrown in the service etc.

So as we see Visual Studio (or command line) proxy generating helps us in many ways but also brings new problems that are hard to solve.

I figured that there has to be a better way to solve this everyday problem so while working on my personal MVVM framework (yes, everyone is building one these days) i was setting these goals regarding the Web Service calls from my MVVM applications:

  1. simplify as much as possible asynchronous invocation of Web Service methods (avoid writing boring boilerplate code for each call)
  2. get rid of the Add Service Reference approach completely if possible
  3. make the Web Services unit testable (hide them behind some interface so we can mock them in our unit tests)
  4. simplify exception handling
  5. fault tolerance (if web service client is faulted by exception it should be automatically recreated)

If this list of features looks interesting to you then you will soon see that all this is possible in a simple way by using ChannelFactory<T> and creating the Web Service client channel for the web service manually.

So lets start: In our example we will be using a fake WeatherForecast web service that will have just one method GetForecast and it will accept DateTime as parameter and return a simple class DailyForecast as a result that will have some fake data just to have something to work with.

First of all we need to create a service contract interface for WeatherForecastWebService and since we must allow the Silverlight client to call this web service asynchronously we will add conditional compilation code regions in the interface with additional asynchronous signatures for the GetForecast method (BeginGetForecast and EndGetForecast) like this:

namespace Abstractions
{
    [ServiceContract]
    public interface IWeatherForecastService
    {

#if SILVERLIGHT
        [OperationContract(AsyncPattern=true)]
        IAsyncResult BeginGetForecast(DateTime day, AsyncCallback callback, object state);
        DailyForecast EndGetForecast(IAsyncResult result);
#else

        [OperationContract]
        DailyForecast GetForecast(DateTime day);
#endif
    }
}

and here is the DailyForecast Data Transfer Object (DTO) class that we will receive from the web service:

namespace Abstractions
{
    [DataContract]
    public class DailyForecast
    {
        [DataMember]
        public DateTime Date { get; set; }

        [DataMember]
        public string Description { get; set; }
    }
}

Note the DataContract and DataMember attributes, they must be provided in order to receive the class on the client properly.

Since we are to consume the web service on the Silverlight client we must make available all the classes to the client side.

Here is how we are going to accomplish this: We must define service contract interface and all the classes that the service will return both on server and on the Silverlight client. We will do that by creating a Abstractions.Web class library project that will hold the service contract interface IWeatherForecastService all the needed Data Transfer Object classes (in this example its just DailyForecast class), and then we will also create Abstractions.Silverlight - Silverlight class library project where we will add the same classes (DTO’s and service contract interface) as links – by going to to right click menu on the project and choose Add -> Existing Item and add all needed files and click on Add As Link button instead of Add button.

here is how this setup looks in my Visual Studio instance: So now that we have same set of shared classes on client and on the server we can proceed with creating a web service helper class that will allow us to invoke asynchronous methods in a simple way without having to do lot of boilerplate code. As we said we want to be able to mock that helper in our Unit Tests we need to have an interface for it so lets define that first:

namespace Framework.Abstractions.Silverlight.WebServices
{
    public interface IWebServiceClientFactory<TWebService> :  IDisposable
    {
        TWebService WebServiceInstance
        {
            get;
        }

        void Invoke<TParam, TResult>(TParam param, object state,
                                     Func<TParam, AsyncCallback, object, IAsyncResult> beginOp,
                                     Func<IAsyncResult, TResult> endOp,
                                     Action<AsyncWebServiceCallResult<TResult>> onComplete);

    }
}

As you can see we are defining the WebServiceClientFactory of TWebService that will expose a web service client instance WebServiceInstance if we want to call it directly but more important will be the generic Invoke method for generic asynchronous calls that will allow to call any method on any web service in a simple way just by specifying the parameter, then the begin and end method we want to calla and a method that should be called with the received results when web service call is finished.

Our helper class will also implement IDisposable so we can cleanup properly.

Let us investigate the Invoke method. From its signature we see that it is a generic function and that it has two type parameters, TParam that is the type of the parameter sent to our web service when we invoke the web method, and TResult that is the type of the result we expect from the method.

Then there is a object state that we want to send to the web service method (we can pass NULL there if we don’t need it).

And then comes the fun part: Parameter beginOp is a BEGIN* method that will be invoked, and parameter endOp is the END* method that will be invoked for the web service call. In our case we will supply here BeginGetForecast and EndGetForecast methods using the WebServiceInstance property of the same factory class. But its important to note here that if our web service would have other methods that support asynchronous invoking with these BEGIN* and END* signatures, we could call them in same way, just passing another pair of Begin* and End* methods.

Last parameters is an Action> that will be called when the web method call is finished. This action will receive the instance of custom generic class AsyncWebServiceCallResult whose type parameter is the DailyForecast – result we would normally expect from the web method. So here is the definition of generic AsyncWebServiceCallResult class:

namespace Framework.Abstractions.Silverlight.WebServices
{
    public class AsyncWebServiceCallResult<TResult>
    {
        public TResult Result { get; set; }
        public bool WasSuccessfull { get; set;}
        public Exception Exception { get; set; }
    }
}

So this class is just a wrapper around the TResult we would usually receive from the web service method call and it adds just two more properties: boolean WasSuccessfull and Exception. If web method call is executed without problems WasSuccessfull is set to true and Exception is null, and on the other hand if there is some exception thrown during the invocation of the web service method call Exception will hold the Exception thrown and WasSuccessfull will be set to false.

So lets see how we would use this Web Service factory to call our WeatherForecastService:

var weatherServiceFactory = SimpleServiceLocator.Instance.Retrieve<IWebServiceClientFactory<IWeatherForecastService>>();
weatherServiceFactory.Invoke(date, null,
                                          weatherServiceFactory.WebServiceInstance.BeginGetForecast,
                                          weatherServiceFactory.WebServiceInstance.EndGetForecast,
                                          this.OnResultReceived);

And the method that will be called when results is received would look like this:

        private void OnResultReceived(AsyncWebServiceCallResult<DailyForecast> asyncResult)
        {
            if (asyncResult.WasSuccessfull)
            {
                this.StatusMessage = "New forecast received ok.";
                this.ForecastThatWasReceived = asyncResult.Result;

            }
            else
            {
                this.ForecastThatWasReceived = null;
                this.StatusMessage = "Error result received: Error description: " + asyncResult.Exception.Message;
            }
        }

And you can use this generic helper class to create wrapper around ANY web service exposed to your Silverlight application.

You just instantiate this class giving it the contract interface of the desired web service and URL of the web service.

WebServiceClientFactory will do all the plumbing for you and create ChannelFactory and web service client and expose it in WebServiceInstance property.

Then you can use Invoke method of the class to call ANY web service method with single line of code (you need on complete action to receive the result but you cannot avoid that – its asynchronous call after all).

Usable?  :)

So now that you have seen how we would use the interface of our web service factory, lets see how its really implemented:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Windows;
using Framework.Abstractions.Silverlight.WebServices;
using System.Linq.Expressions;

namespace Framework.Implementors.Silverlight.WebServices
{
    public class WebServiceClientFactory<TWebService> : IWebServiceClientFactory<TWebService> where  TWebService : class
    {
        private CustomBinding binding;
        private readonly string endpointAddress;
        private ChannelFactory<TWebService> channelFactory;

        public WebServiceClientFactory(CustomBinding binding, string endpointAddress)
        {
            this.binding = binding;
            this.endpointAddress = endpointAddress;
        }

        public WebServiceClientFactory(string endpointAddress)
        {
            this.endpointAddress = endpointAddress;
        }

        public TWebService WebServiceInstance
        {
            get
            {
                if (this.channelFactory == null || this.channel == null)
                {
                    this.InitializeWeatherServiceClient();
                }

                return this.channel;
            }

            private set
            {
                this.channel = value;
            }
        }
        private TWebService channel;

        private void InitializeWeatherServiceClient()
        {
            Debug.WriteLine("Initializing factory and channel in " + this.GetType().Name);
            if (this.binding == null)
            {
                var elements = new List<BindingElement>();
                elements.Add(new BinaryMessageEncodingBindingElement());
                elements.Add(new HttpTransportBindingElement());
                this.binding = new CustomBinding(elements);
            }

            channelFactory = new ChannelFactory<TWebService>(this.binding, new EndpointAddress(endpointAddress));
            channel = this.GetNewChannelFromCurrentFactory();
        }

        public void Invoke<TParam, TResult>(TParam param, object state, Func<TParam, AsyncCallback, object, IAsyncResult> beginOp, Func<IAsyncResult, TResult> endOp, Action<AsyncWebServiceCallResult<TResult>> onComplete)
        {
            beginOp(param, (ar) =>
                {
                    var asyncResult = new AsyncWebServiceCallResult<TResult>();
                    try
                    {
                        asyncResult.Result = endOp(ar);
                        asyncResult.WasSuccessfull = true;
                    }
                    catch (Exception e)
                    {
                        asyncResult.WasSuccessfull = false;
                        asyncResult.Exception = e;
                    }

                    if (Deployment.Current.Dispatcher.CheckAccess())
                    {
                        onComplete(asyncResult);
                    }
                    else
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() => onComplete(asyncResult));
                    }

                }, state );
        }

        private TWebService GetNewChannelFromCurrentFactory()
        {

            var newChannel = channelFactory.CreateChannel();

            var channelAsCommunicationObject = (newChannel as ICommunicationObject);
            if (channelAsCommunicationObject != null)
            {
                channelAsCommunicationObject.Faulted += ChannelFaulted;
            }

            return newChannel;
        }

        void ChannelFaulted(object sender, EventArgs e)
        {
            Debug.WriteLine("Service channel faulted in " + this.GetType().Name);
            var communicationObject = (this.channel as ICommunicationObject);
            if (communicationObject != null)
            {
                communicationObject.Abort();

                this.channel = this.GetNewChannelFromCurrentFactory();
            }
        }

        ~WebServiceClientFactory()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
        }

        protected void Dispose(bool disposing)
        {
            if (disposing)
            {
                // dispose managed stuff
                Debug.WriteLine("Disposing managed resources in " + this.GetType().Name);
                var communicationObject = (this.channel as ICommunicationObject);
                if (communicationObject != null)
                {
                    communicationObject.Faulted -= this.ChannelFaulted;

                    try
                    {
                        communicationObject.Close();
                    }
                    catch (Exception)
                    {
                        try
                        {
                            communicationObject.Abort();
                        }
                        catch
                        {
                        }
                    }
                }
            }

            // here we would dispose unmanaged stuff
        }

    }
}

Class has multiple constructors so you can choose how to set it up. The simplest usage is just to specify the string URL of the web service. Here is how i setup my IOC in the bootstrapper of my Silverlight application:

SimpleServiceLocator.Instance.RegisterAsSingleton<IWebServiceClientFactory<IWeatherForecastService>>
(new WebServiceClientFactory<IWeatherForecastService>("http://localhost:1000/WeatherForecastService.svc"));

When constucted like this factory class uses standard Binding that would be created for you if you would add the Web Service Reference from visual studio and it will use that Binding and that given URL as endpoint to create a generic ChannelFactory of the web service type provided in type param

<TWebService> and then it will create a communication channel to communicate with web service of given type on the given URL.

Here is the code that is doing this part:

        private void InitializeWeatherServiceClient()
        {
            Debug.WriteLine("Initializing factory and channel in " + this.GetType().Name);
            if (this.binding == null)
            {
                var elements = new List<BindingElement>();
                elements.Add(new BinaryMessageEncodingBindingElement());
                elements.Add(new HttpTransportBindingElement());
                this.binding = new CustomBinding(elements);
            }

            channelFactory = new ChannelFactory<TWebService>(this.binding, new EndpointAddress(endpointAddress));
            channel = this.GetNewChannelFromCurrentFactory();
        }

There is a another constructor that accepts Binding if you want to provide your own.
Next interesting part of the class is the Invoke method:

        public void Invoke<TParam, TResult>(TParam param, object state, Func<TParam, AsyncCallback, object, IAsyncResult> beginOp, Func<IAsyncResult, TResult> endOp, Action<AsyncWebServiceCallResult<TResult>> onComplete)
        {
            beginOp(param, (ar) =>
                {
                    var asyncResult = new AsyncWebServiceCallResult<TResult>();
                    try
                    {
                        asyncResult.Result = endOp(ar);
                        asyncResult.WasSuccessfull = true;
                    }
                    catch (Exception e)
                    {
                        asyncResult.WasSuccessfull = false;
                        asyncResult.Exception = e;
                    }

                    if (Deployment.Current.Dispatcher.CheckAccess())
                    {
                        onComplete(asyncResult);
                    }
                    else
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() => onComplete(asyncResult));
                    }

                }, state );
        }

As you can see no big deal there, we just invoke the BEGIN* operation with lambda method as complete handler where we wrap the call to END* operation in Try..Catch so we can recover from any exception.
If there was an exception we set WasSuccessfull to false and Exception property.
If all went ok we populate the Result property with the result of the web method call and then we invoke the onComplete action that was supplied by the user of the class.
But we make sure that we invoke it on the UI thread just as a convenience for the user so he does not need to do it by himself.

One more important thing is that if our web service channel gets faulted by some communication error we will catch that event and recreate the channel:

        void ChannelFaulted(object sender, EventArgs e)
        {
            Debug.WriteLine("Service channel faulted in " + this.GetType().Name);
            var communicationObject = (this.channel as ICommunicationObject);
            if (communicationObject != null)
            {
                communicationObject.Abort();

                this.channel = this.GetNewChannelFromCurrentFactory();
            }
        }

Previously, we subscribed that method to the OnFaulted event on the channel.

Other parts of the class are not too much interesting so you can dig yourself if you want.

So lets see how we would use the class in our view model.
Here is the listing of the ForecastViewModel that will allow us to invoke the WeatherForecast web service:

using System;
using Abstractions;
using Framework.Abstractions.Silverlight.Intefaces;
using Framework.Abstractions.Silverlight.WebServices;
using Framework.Implementors.Silverlight.Comanding;
using Framework.Implementors.Silverlight.MVVM;

namespace ViewModels
{
    public class ForecastViewModel : ViewModel
    {
        private readonly IWebServiceClientFactory<IWeatherForecastService> weatherServiceFactory;

        public ForecastViewModel(IWebServiceClientFactory<IWeatherForecastService> weatherServiceFactory)
        {
            this.weatherServiceFactory = weatherServiceFactory;

            this.GetForecastCommand =
                new DelegateCommand<DateTime>(
                    date =>
                    {
                        this.StatusMessage = string.Format("Invoking web service with parameter {0}", date.ToString());
                        this.weatherServiceFactory.Invoke(
date,
null,
this.weatherServiceFactory.WebServiceInstance.BeginGetForecast,

this.weatherServiceFactory.WebServiceInstance.EndGetForecast,

this.OnResultReceived);

                    });

        }

        private void OnResultReceived(AsyncWebServiceCallResult<DailyForecast> asyncResult)
        {
            if (asyncResult.WasSuccessfull)
            {
                this.StatusMessage = "New forecast received ok.";
                this.ForecastThatWasReceived = asyncResult.Result;

            }
            else
            {
                this.ForecastThatWasReceived = null;
                this.StatusMessage = "Error result received: Error description: " + asyncResult.Exception.Message;
            }
        }

        private IDelegateCommand getForecastCommand;

        public IDelegateCommand GetForecastCommand
        {
            get { return getForecastCommand; }
            set { getForecastCommand = value;
                this.OnPropertyChanged("GetForecastCommand");
            }
        }

        private DailyForecast forecastThatWasReceived;

        public DailyForecast ForecastThatWasReceived
        {
            get { return forecastThatWasReceived; }
            set { forecastThatWasReceived = value;
            this.OnPropertyChanged("ForecastThatWasReceived");
            }
        }

        public DateTime ValidForecastDate
        {
            get
            {
                return DateTime.Now;
            }
        }

        public DateTime BadForecastDate
        {
            get
            {
                return DateTime.MinValue;
            }
        }

        private string statusMessage;
        public string StatusMessage
        {
            get { return statusMessage; }
            set { statusMessage = value;
            this.OnPropertyChanged("StatusMessage");
            }
        }
    }
}

As you can see from the ForecastViewModel we have a command that’s invoking the web service called GetForecastCommand and we have a action method OnResultReceived that receives the result.

If the web service call fails we set the ForecastThatWasReceived to null and we set the StatusMessage to the Message of the Exception we received from server.

So here is our simple ForecastView:

<UserControl x:Class="Views.ForecastView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400" MinHeight="400" MinWidth="400">

    <Grid x:Name="LayoutRoot" Background="Red">

        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <StackPanel Orientation="Vertical" Grid.Row="0">
            <Button Content="Invoke valid web service call" Command="{Binding GetForecastCommand}" CommandParameter="{Binding ValidForecastDate}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="10" />

            <Button Content="Invoke web service call that throws exception on server" Command="{Binding GetForecastCommand}" CommandParameter="{Binding BadForecastDate}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="10" />

        </StackPanel>

        <Grid Grid.Row="1">
            <StackPanel Orientation="Vertical">
                <TextBlock Text="{Binding ForecastThatWasReceived.Date, StringFormat='Date: {0}', FallbackValue=' ?'}" />
                <TextBlock Text="{Binding ForecastThatWasReceived.Description, StringFormat='Description: {0}', FallbackValue=' ?'}" />

            </StackPanel>
        </Grid>

        <Grid Grid.Row="2">
            <TextBlock Text="{Binding StatusMessage}" TextWrapping="Wrap" />

        </Grid>

    </Grid>
</UserControl>

As you can see we have two buttons, each wired up to the same GetForecastCommand but with different parameters.
One is sending the current date to the server and other is using the BadForecastDate databound from ViewModel which is set to DateTime.Min. When web service receives any other date then DateTime.Min it returns valid instance of DailyForecast class and if it receives DateTime.Min it throws some bogus exception.
This is how we will test our WebServiceFactory class to see if it can handle the exceptions thrown on server side or not.

you can test the live sample application here.

So here is screenshot of the app (in case you dont have the Silverlight 4 runtime installed) when we invoke the web service with current date:

As you can see when we click on first button we receive the valid forecast and when we click the second one, we will receive the error but it will be catched and wrapped in our AsyncWebServiceCallResult class and our UI won’t hang and we will be able to recover from that error and immediately invoke the web service call again with different parameters.

Here is the same app when we invoke the web service method with invalid (min) date so it throws exception:

So this should help us handle the web service with greater ease right ? :D

But wait! We are not finished yet! Those of you that were paying attention noticed i promised a unit testable web services.

So lets do that also.

We will add another SIlverlight application to our sample code and set it up with Silverlight Unit Testing Framework.

Also we will reference all the needed projects – ViewModels, Abstractions.Silverlight, Framework.Abstractions and Framework.Implementors.

Also we need to make a fake WebServiceClientFactory and IWeatherService implementations so we can use them in our tests instead of the real implementations.

So lets do that first. here is the FakeWebServiceClientFactory:

using System;
using Abstractions;
using Framework.Abstractions.Silverlight.WebServices;

namespace Silverlight.Tests
{
    public class FakeWebServiceClientFactory : IWebServiceClientFactory<IWeatherForecastService>
    {
        public FakeWebServiceClientFactory()
        {
            this.WebServiceInstance = new FakeWeatherService();
        }

        public void Dispose()
        {
            throw new NotImplementedException();
        }

        public IWeatherForecastService WebServiceInstance { get; private set; }

        public object LastParameterSentToInvoke;

        public object NextResultToReturn;

        public void Invoke<TParam, TResult>(TParam param, object state, Func<TParam, AsyncCallback, object, IAsyncResult> beginOp, Func<IAsyncResult, TResult> endOp, Action<AsyncWebServiceCallResult<TResult>> onComplete)
        {
            this.LastParameterSentToInvoke = param;

            var nextResult = NextResultToReturn as AsyncWebServiceCallResult<TResult>;

            if (nextResult != null)
            {
                onComplete(nextResult);
            }
            else
            {
                onComplete(new AsyncWebServiceCallResult<TResult>
                               {Exception = new Exception("Some exception"), WasSuccessfull = false});
            }
        }
    }
}

As you can see it does not do much, its just a manually written mock class we can use in our test instead of the real web service client factory.
It allows us to check what was sent to the Invoke method as parameter and it allows us to set what will be sent to the OnComplete handler when client code invokes some web service call.

Also we need a stub for the IWeatherForecastService so here it is:

using System;
using Abstractions;

namespace Silverlight.Tests
{
    public class FakeWeatherService : IWeatherForecastService
    {
        public IAsyncResult BeginGetForecast(DateTime day, AsyncCallback callback, object state)
        {
            throw new NotImplementedException();
        }

        public DailyForecast EndGetForecast(IAsyncResult result)
        {
            throw new NotImplementedException();
        }
    }
}

Again its very simple its just a Stub class that allows us to instantiate and use it without really calling it.
So now we can write few tests for our ForecastViewModel:

using System;
using Abstractions;
using Framework.Abstractions.Silverlight.WebServices;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ViewModels;

namespace Silverlight.Tests
{
    [TestClass]
    public class ForecastViewModelTests
    {
        [TestMethod]
        public void GetForecastCommand_WhenExecutedWithParam_InvokesCallOnWebServiceClientFactoryInstance()
        {
            var fakeFactory = new FakeWebServiceClientFactory();
            var viewModel = new ForecastViewModel(fakeFactory);

            var date = DateTime.Now;

            viewModel.GetForecastCommand.Execute(date);

            Assert.AreEqual(date, fakeFactory.LastParameterSentToInvoke);
        }

        [TestMethod]
        public void GetForecastCommand_WhenExecutedWithMinDateANdWebserviceReturnsUnsuccessfullResult_SetsTheForecastThatWasReceivedToNull()
        {
            var fakeFactory = new FakeWebServiceClientFactory();
            var viewModel = new ForecastViewModel(fakeFactory);
            viewModel.ForecastThatWasReceived = new DailyForecast() {Description = "just dummy so we can test if it was set to null."};

            fakeFactory.NextResultToReturn = new AsyncWebServiceCallResult<DailyForecast>() {WasSuccessfull = false, Exception = new Exception("Bad error.")};
            viewModel.GetForecastCommand.Execute(DateTime.MinValue);

            Assert.IsNull(viewModel.ForecastThatWasReceived);
        }

        [TestMethod]
        public void GetForecastCommand_WhenExecutedWithMinDateANdWebserviceReturnsUnsuccessfullResult_SetsTheStatusMessageToErrorFromReturnedException()
        {
            var fakeFactory = new FakeWebServiceClientFactory();
            var viewModel = new ForecastViewModel(fakeFactory);
            viewModel.ForecastThatWasReceived = new DailyForecast() { Description = "just dummy so we can test if it was set to null." };

            fakeFactory.NextResultToReturn = new AsyncWebServiceCallResult<DailyForecast>() { WasSuccessfull = false, Exception = new Exception("Bad error.") };
            viewModel.GetForecastCommand.Execute(DateTime.MinValue);

            Assert.IsTrue(viewModel.StatusMessage.Contains("Bad error."));
        }

        [TestMethod]
        public void GetForecastCommand_WhenExecutedWithOkDateANdWebserviceReturnsSuccessfullResult_SetsTheStatusMessageToOkMessage()
        {
            var fakeFactory = new FakeWebServiceClientFactory();
            var viewModel = new ForecastViewModel(fakeFactory);
            viewModel.ForecastThatWasReceived = null;

            fakeFactory.NextResultToReturn = new AsyncWebServiceCallResult<DailyForecast>() { WasSuccessfull = true};
            viewModel.GetForecastCommand.Execute(DateTime.Now);

            Assert.IsTrue(viewModel.StatusMessage.Contains("New forecast received ok."));
        }

    }
}

And when we run them, as you can see from the screenshot below, they are all GREEN!

So there you go, we have completed in this lengthy posts most of the tasks we set in the beginning. Off course there are many places for improvement but the basis of a simple way to invoke WCF web services from Silverlight and MVVM and Unit Testability are there.

If you have some comments and improvements to the solutions presented here i would be happy to hear them out.

You can download Visual Studio 2010 Solution with the code from this post if you want to run it locally.

Until then, happy testing!

Binding UI Events from View to commands in ViewModel in Silverlight 4

In previous two posts we covered wiring up the Views and ViewModels and Blendability and showing ModalDialogs in MVVM way.

Today we will touch another problem that people starting with MVVM very often fail to address properly:

Handling the UI Events of the View in the ViewModel while avoiding placing any logic in code behind of the View.

So our design goals for this post are:

  • We want to be able to wire-up UI Events to the commands in ViewModel via DataBinding in Xaml without any code behind in the View
  • View should not be aware of the ViewModel’s type or any other details of its existence – View should just use Silverlight’s DataBinding to access its ViewModel public properties (its DataContext) regardless of what is actually set to be there
  • We want to be able to handle any event that occurs in View (that includes not only Button clicks but also Mouse events,  Drag and Drop events, Loaded events etc).

When i was trying to solve this problem, i made a mistake.

I coupled the View with ViewModel,  made the View aware of the ViewModel via interface of the ViewModel.

View held the instance of ViewModel in its DataContext.

And then when some event fires in the View i would call a ViewModel method in code behind of the View (accessing it via local variable holding the ViewModel instance casted to interface that ViewModel is implementing).

While this approach works for all events in the View because you can create event handler for any View event, it has many drawbacks.

Main problems are:

  • View has to know about the ViewModel and it has to have a instance of the ViewModel injected somehow
  • we have to create event handlers in the View code behind .cs file for each event (this can be really boring, and im lazy to do repetitive code so that was really hard for me).

I didn’t like this solution at all and I immediately abandoned it.

Then i tried searching for possible solutions on the web and found the magical Expression Blend Samples.

Microsoft introduced Behaviors in Silverlight 3 with Blend 3 to help UI designers to have a flexible new way to add interactivity to applications.

Behaviors allow interactivity to be added to elements directly on the design surface in XAML without having to write additional code.

I will not go into details on Behaviors since there are tons of resources on the web on the subject,  you can read the original Blend 3 Behaviors announcement to get more info.

The great thing about Behaviors is that they introduced Triggers and very handy  EventTrigger and TriggerAction classes that are perfect match for our MVVM events scenario.

As you can read on the MSDN link EventTrigger  ‘Represents a trigger that applies a set of actions … in response to an event’.

So we can create a EventTrigger for some UI event in our View that will fire a custom TriggerAction that will call a method on our ViewModel with some parameters.

On the mentioned Expression Blend Samples page there is already implemented basic class for this – its called InvokeDataCommand and we will just customize it and extend (generalize it) so it serves our needs.

In the end we want to accomplish something like this in our View’s Xaml:

    <Interactivity:Interaction.Triggers>
        <Interactivity:EventTrigger EventName="MouseMove">
            <TriggerActions:MapMouseEventToCommand Command="{Binding Path=ShowMousePositionCommand}" />
        </Interactivity:EventTrigger>
    </Interactivity:Interaction.Triggers>

So this is instructing our View to call the command called ShowMousePositionCommand on its ViewModel when mouse pointer is moved over some control.

So lets get started!

First we need to create a command class that we will be able to call from our Events.

Silverlight has only partial support for commanding.

Until Silverlight 4 ICommand interface was available – but without any real support or use.
In Silverlight 4 this interface is supported by Button type controls in again partial way:  in ButtonBase class from which all button-like controls inherit, there are two properties: Command and CommandParameter that you can point to a command that implements ICommand interface and pass it some parameter.

This can be done via DataBinding and when you click the button this command will be executed with the specified parameter. No code solution, pure XAML!
The problem is that Silverlight 4 Beta does not offer any implementation of the ICommand interface so we have to do this by ourselves.

Here is the ICommand interface:

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

So it basically defines a contract: Any command that will implement this interface we we will be able to query it if we can ececute it (CanExecute) and execute it with parameter via its Execute method,  also there is an event CanExecuteChanged so that anyone can subscribe to it in order to be notified if CanExecute status of command has changed (this is used by UI controls so that buttons become disabled if command is disabled etc).

But before we implement this lets make a slight modification and create another interface IDelegateCommand that will implement ICommand interface and just add one method RaiseCanExecuteChanged();

This new method is there so that we can invoke it from code if we know that status of our command has changed – so by invoking it we can notify the UI of this change.

So here is the new IDelegateCommand interface:

    public interface IDelegateCommand : ICommand
    {
        void RaiseCanExecuteChanged();
    }

And here is our generic version of DelegateCommand class that implements IDelegateCommand and ICommand:

  public class DelegateCommand<T> : IDelegateCommand
  {
    private readonly Action<T> executeAction;
    private readonly Func<T, bool> canExecuteAction;

    public DelegateCommand(Action<T> executeAction, Func<T, bool> canExecuteAction)
    {
      this.executeAction = executeAction;
      this.canExecuteAction = canExecuteAction;
    }

    public DelegateCommand(Action<T> executeAction) : this(executeAction, null)
    {
    }

    /// <summary>
    /// Defines the method that determines whether the command can execute in its current state.
    /// </summary>
    /// <returns>
    /// true if this command can be executed; otherwise, false.
    /// </returns>
    /// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null. </param>
    public bool CanExecute(object parameter)
    {
      if (canExecuteAction != null)
      {
        return canExecuteAction((T) parameter);
      }
      return true;
    }

    /// <summary>
    /// Defines the method to be called when the command is invoked.
    /// </summary>
    /// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null. </param>
    public void Execute(object parameter)
    {
      if (CanExecute(parameter))
      {
        executeAction((T) parameter);
      }
    }

    protected void OnCanExecuteChanged(object sender, EventArgs args)
    {
        var handler = this.CanExecuteChanged;
        if (handler != null)
        {
            handler(sender, args);
        }
    }

    public void RaiseCanExecuteChanged()
    {
        this.OnCanExecuteChanged(this, EventArgs.Empty);
    }

    public event EventHandler CanExecuteChanged;
  }

Its simple generic class that allows us to create commands on our ViewModels that will be triggered when needed.

I wont go into much details of this class since there are a lot of posts on this on the web. Be sure to check out Prism DelegateCommand version since my implementation is mostly based on their code.

Now that we have a way of specifying the commands that we will trigger let’s see how we will trigger them.

Back to our Behaviors:  We will create base generic class that will inherit from TriggerAction<FrameworkElement> and we will use this class to build specific TriggerActions for different UI events:

    public abstract class MapEventToCommandBase<TEventArgsType> : TriggerAction<FrameworkElement>
        where TEventArgsType : EventArgs
    {
        public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(IDelegateCommand), typeof(MapEventToCommandBase<TEventArgsType>), new PropertyMetadata(null, OnCommandPropertyChanged));
        public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register("CommandParameter", typeof(object), typeof(MapEventToCommandBase<TEventArgsType>), new PropertyMetadata(null, OnCommandParameterPropertyChanged));

        private static void OnCommandParameterPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var invokeCommand = d as MapEventToCommand;
            if (invokeCommand != null)
            {
                invokeCommand.SetValue(CommandParameterProperty, e.NewValue);
            }
        }

        private static void OnCommandPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var invokeCommand = d as MapEventToCommand;
            if (invokeCommand != null)
            {
                invokeCommand.SetValue(CommandProperty, e.NewValue);
            }
        }

        protected override void Invoke(object parameter)
        {
            if (this.Command == null)
            {
                return;
            }

            if (this.Command.CanExecute(parameter))
            {
                var eventInfo = new EventInformation<TEventArgsType>
                                    {
                                        EventArgs = parameter as TEventArgsType,
                                        Sender = this.AssociatedObject,
                                        CommandArgument = GetValue(CommandParameterProperty)
                                    };
                this.Command.Execute(eventInfo);
            }
        }

        public IDelegateCommand Command
        {
            get
            {
                return (IDelegateCommand)base.GetValue(CommandProperty);
            }
            set
            {
                base.SetValue(CommandProperty, value);
            }
        }

        public object CommandParameter
        {
            get
            {
                return base.GetValue(CommandParameterProperty);
            }
            set
            {
                base.SetValue(CommandParameterProperty, value);
            }
        }
    }

Our MapEventToCommandBase class simply adds Command and CommandParameter DependencyProperties so we can set via DataBinding the command and (optionally) parameter for the event.
It has one type parameter TEventArgsType that it uses so it can send the appropriate EventArgs from the Event that occurred to the command we are calling.
That is why TEventArgsType has a constraint that it has to inherit from EventArgs since every UI event sends some information in a class that inherits from EventArgs or sends EventArgs.Empty.

The meat of this class is the method Invoke that overrides the method in its base class TriggerAction.
This method is called from the Silverlight runtime when some event occurs in the UI and the parameter sent is the instance of class that inherits from EventArgs and carries the information specific to that event (MouseEventArgs, DragEventArgs, KeybardEventArgs etc).

What we do in this method is that we take that event information we received and pack it into new class that we will send to our command.

Its this part of code:

            if (this.Command.CanExecute(parameter))
            {
                var eventInfo = new EventInformation<TEventArgsType>
                                    {
                                        EventArgs = parameter as TEventArgsType,
                                        Sender = this.AssociatedObject,
                                        CommandArgument = GetValue(CommandParameterProperty)
                                    };
                this.Command.Execute(eventInfo);
            }

So we construct the instance of generic EventInformation class of certain EventArgs inheritor type and we include there the sender of the event and the optional argument we sent from XAML binding.

Here is how the generic EventInformation class looks like:

    public class EventInformation<TEventArgsType> where TEventArgsType : EventArgs
    {
        public object Sender { get; set; }
        public TEventArgsType EventArgs { get; set; }
        public object CommandArgument { get; set; }
    }

It allows us to easily create strongly typed class for each of possible events that can occur in the UI.
For RoutedEvents like Loaded event the RoutedEventArgs will be passed there.

Lets continue. Since our MapEventToCommandBase is abstract and generic class we need to inherit it to be able to actually use it in Xaml so here are some examples of concrete MapSOMEKINDOFEventToCommand implementations:

First MapMouseEventToCommand:

    public class MapMouseEventToCommand : MapEventToCommandBase<MouseEventArgs>
    {

    }

So as you see there is nothing we need to implement here, just to specify the type of the event we want to handle.
If Xaml would support generics we could make the MapEventToCommandBase not to be abstract and use it directly but until Xaml learns to accept generics this is the best way i could figure out.

Then there is the MapKeyboardEventToCommand:

    public class MapKeyboardEventToCommand : MapEventToCommandBase<KeyEventArgs>
    {

    }

So we can do this for any type of event that we need (see the sample Visual Studio 2010 Project for more examples)

If we don’t need the specific EventArgs we can also use the MapEventToCommand class that uses EventArgs as its type so it can be used with ANY event.
The drawback is that in the command we will receive the EventInformation<EventArgs> so we need to cast the EventArgs property of that class to some specific EventArgs inheritor class so we lose type safety.

So now that all is in place lets see how we can use our new magic classes from Xaml in Views.

First the simplest event: Loaded.

In Xaml of our View we must place this code:

    <Interactivity:Interaction.Triggers>
        <Interactivity:EventTrigger EventName="Loaded">
            <TriggerActions:MapEventToCommand Command="{Binding Path=LoadedCommand}" CommandParameter="Shell view loaded at {0:d/M/yyyy HH:mm:ss:fff tt}" />
        </Interactivity:EventTrigger>
    </Interactivity:Interaction.Triggers>

So we are creating EventTrigger for event with name “Loaded” and for this event we are setting TriggerAction to our MapEventToCommand. This event will trigger when control is loaded and since we use DataBinding to set the Command property, when the event occurs, LoadedCommand on our DataContext will be invoked with the string parameter we hard coded in CommandParameter (we could used DataBinding there also but i skipped this for now to keep things simple).

Next, in our ViewModel we have to define the actual LoadedCommand command.

Important note: DO NOT FORGET to always use OnPropertyChanged in the command’s property setter if you want all of this to work properly:

        private ICommand loadedCommand;
        public ICommand LoadedCommand
        {
            get { return loadedCommand; }
            private set
            {
                loadedCommand = value;
                this.OnPropertyChanged("LoadedCommand");
            }
        }

Another note: we are defining our command as ICommand property and later we will set them with DelegateCommands instances but this is off course perfectly fine since DelegateCommand implements IDelegateCommand that implements ICommand interface.

And in the constructor of ViewModel with single lambda we added the actual code that will run when command is executed (we just set some string property called LoadedTime to the current DateTime formated by the format text given in the parameter).

Since the View is bound to this LoadedTime property it’s shown on the control when its changed, triggered by INotifyPropertyChanged:

        this.LoadedCommand
            = new DelegateCommand<EventInformation<EventArgs>>
                (p =>
                     {
                         LoadedTime = string.Format(p.CommandArgument.ToString(), DateTime.Now);
                     });

Lets see how we would map a MouseMove event:

    <Interactivity:Interaction.Triggers>

        <Interactivity:EventTrigger EventName="MouseMove">
            <TriggerActions:MapMouseEventToCommand Command="{Binding Path=ShowMousePositionCommand}" />
        </Interactivity:EventTrigger>

    </Interactivity:Interaction.Triggers>

So we are doing the same thing here only we are using MapMouseEventToCommand in stead of the basic MapEventToCommand – we are doing this so we get strongly typed MouseEventArgs from the original event passed as EventArgs parameter in the EventInformation class that will be passed to the command.

Here is the command definition from our ViewModel:

        private ICommand showMousePositionCommand;
        public ICommand ShowMousePositionCommand
        {
            get { return showMousePositionCommand; }
            set { showMousePositionCommand = value;
            this.OnPropertyChanged("ShowMousePositionCommand");

            }
        }

And here is part of the ViewModel constructor where we actually define the code triggered inside the command:

        this.ShowMousePositionCommand
            = new DelegateCommand<EventInformation<MouseEventArgs>>(
            p =>
            {
                this.MousePosition = string.Format("x:{0} y:{1}",
                    p.EventArgs.GetPosition(null).X, p.EventArgs.GetPosition(null).Y);
            });

What happens here is that when our command is invoked (this is triggered when user moves his mouse pointer in our View) we use the received MouseEventArgs (from EventArgs property) of the EventInformation instance to get the current mouse position and we create a string representation of it and we set a public property on our ViewModel.

And our View is again data-bound to this property – so it will get notification that its value has changed and re-display it on screen so we will have realtime coordinates of our mouse pointer displayed in the view as we move the pointer.

Check out the demo application to see this in action.

So we managed to wire up events from View to the ViewModel in Xaml via DataBinding.

Here is how our View’s backend code .cs file looks like:

using System.Windows.Controls;

namespace EventCommands.Views
{
    public partial class ShellView : UserControl
    {
        public ShellView()
        {
            InitializeComponent();
        }
    }
}

As you can see we added zero logic to our View – its only code generated by the Visual Studio when we created the UserControl for the, so its clean design, decoupled View from the ViewModel, and we can later change our Views and our ViewModels won’t event notice ;)

For those that do not have Silverlight 4 installed yet, here is the screen shot of the running demo application showing all the code we have written for this experiment:

If you run the application you will see two independent instances of the small sample EventsWidget for showing Events triggered on View.

Currently im demonstrating MouseMove event, DragAndDrop event, KeyDown event and also Loaded event.

Other UI events can be easily added and are completely supported by the given code.

I deliberately added two instances of same widget on the main page so its clear that data binding works independently and that each control can has its own ViewModel and DataBinds events to Commands in its own ViewModel.

In same way the main control (ShellView) has its own ViewModel and its own Events DataBound to commands in its own ViewModel etc.

You can download the sample application Visual Studio 2010 solution here.