Silverlight 4 - MVVM with Commanding and WCF RIA Services

Note: The code example in this post uses Silverlight 4 PDC Beta and WCR RIA Services PDC Beta, so some changes can be made before RTM.


In my previous post I wrote about “WCF RIA Services and a guide to use DTO/”Presentation Model””, and mention that I will later write a blog post about using a ViewModel. In this post I will show you how you can create a ViewModel and use Silverlight 4 Commanding to use the MVVM pattern. In this blog post I will use Unity as my Dependency Injection framework to inject my Repository to the DomainService, to make this possible we need to create our own DomainServiceFactory, check out my “WCF RIA Services Unity DomainServiceFactory” for information about how to use Unity and Dependency Injection, because I will not cover it in this post.

Architecture and design in this post

The following figure will show you the architecture and design I often use when building Rich Internet Applications:

image

 

In this post the Service Layer will be a DomainService using WCF RIA Services, the Domain Model will be a very simple, just have a Customer entity and a CustomerRepository. The follow if a class diagram of the Customer entity:

image
The following code is the CustomerRepository interface:

 

  public interface ICustomerRepository
  {
     Customer GetCustomerByID(int customerID);

     void Update(Customer customer);
  }

 

Note: This post will not focus on how the ICustomerRepository is implemented, assume it used Entity Framework, Linq to SQL, nHibernate or ADO.NET etc. It’s not important to know in this blog post.

The following code is the Service Layer, where WCF RIA Services DomainService is used and where the ICustomerRepository should be injected:

 [EnableClientAccess()]
 public class CustomerService : DomainService
 {
      private ICustomerRepository _customerRepository;

      public CustomerService(ICustomerRepository customerRepository)
      {
          _customerRepository = customerRepository;
      }

      public CustomerDto GetCustomerByID(int customerID)
      {
          var customer = _customerRepository.GetCustomerByID(customerID);

          return MapCustomerToCustomerDto(customer);
      }

      public void UpdateCustomer(CustomerDto customer)
      {
          if (customerDto == null)
              throw new ArgumentNullException("customer");

          _customerRepository.Update(MapCustomerDtoToCustomer(customerDto));
      }
  }


As you may notice there is a mapping (translator) between the domain Entity Customer to CustomerDto (Data transfer object). If we have used WCF, we would map our domain entity to the DataContract. Frameworks like the AutoMapper could for example be used here instead of manual mapping. In a small Intranet application where the internal bandwidth is good and we don’t have a lot of business logic, we could simply use our Customer and by  pass the mapping. But it all depends on the application we are building, there are so many factors included before we can decide the proper design for our application. So this post is not showing any Silver Bullets, they aren’t any. The following is the code for the CustomerDto, some validation annotation is used on the DTO, when using a ViewModel this validation could instead be added as “real” code to the ViewModel, if we do so, the validation will be executed when we write a test against our ViewModel. But in this example code, I decide that I don’t need to include data rules as part of the test.

 public class CustomerDto
 {
     [Key]
     public int CustomerID { get; set; }

     [Required]
     [StringLength(32, MinimumLength=2)]
     public string FirstName { get; set; }

     [Required]
     [StringLength(32, MinimumLength = 2)]
     public string LastName { get; set; }

     public int Age { get; set; }
}

 

Note: I will use my own DomainServiceFactory to make sure ICustomerRepository will be injected when the CustomerService is created, you can read more about it here.

Now the serer-side and Service layer is completed we can leave it and continue with the client implementation where a ViewModel is going to be used and also Silverlight 4’s Commanding.

ViewModel

A ViewModel is a representation of the View but as a class. Think of the movie Matrix, they only saw a lot of characters moving on the screens, but by looking at them, they saw the world. Think of the ViewModel class as the characters and by looking at it we should see the View. The reason to use a ViewModel is separation of concerns, we don’t want to have logic added to the view. With this separation we could also write automated test to test our View even if the UI isn’t in place.

Here is a skeleton of the ViewModel where Commanding is used:

    public class CustomerViewModel : ViewModel
    {
        public CustomerViewModel()
        {
        }

        public string FirstName
        {
            get;
            set;
        }

        public string LastName
        {
            get;
            set;
        }

        public bool IsAdult
        {
            get;
        }
        public bool IsLoading
{
           get;
internal set;
}
        public ICommand Save
        {
            get;
        }
    }


The ViewModel represents a View which should display two Input fields for FirstName and LastName, and also a read-only checkbox if the Customer is an adult or not. The View should also have a Save button. The IsLoading is used to show or hide a BusyIndicator. Here is the UI of the View which will use the ViewModel:

 image


The following is the XAML for the View, where no code-behind is needed, instead a ViewModel is added as a resource and the data binding feature is used to bind the View to the ViewModel:

<UserControl
xmlns:my="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit"
x:Class="SilverlightApplication1.MainPage" 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" xmlns:vm="clr-namespace:SilverlightApplication1.ViewModels" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400"> <UserControl.Resources> <vm:CustomerViewModel x:Name="customerViewModel"/> </UserControl.Resources> <Grid x:Name="LayoutRoot" DataContext="{StaticResource customerViewModel}"> <my:BusyIndicator IsBusy="{Binding IsLoading}"></my:BusyIndicator> <TextBox Text="{Binding FirstName, Mode=TwoWay, NotifyOnValidationError=True}" ... /> <TextBox Text="{Binding LastNaem, Mode=TwoWay, NotifyOnValidationError=True}" ... /> <TextBlock Text="First Name:" .../> <TextBlock Text="Last Name:" .../> <CheckBox IsChecked="{Binding IsAdult}" Content="Is Adult" .../> <Button Command="{Binding Save}" Content="Save" ... /> </Grid> </UserControl>

ViewModel implementation

You have probably notice that the CustomerViewModel inherits the ViewModel class, the ViewModel class implements the the INotifyPropertyChanged and INotifyDataErrorInfo. You can find the implementation of the ViewModel on my other post about INotifyDataErrorInfo class. In the CustomerViewModel constructor there is a call to the WCF RIA Services to get a specific Customer, because the operation is asynchronous we can’t know how long it will take before the Customer is loaded, so the IsLoading property is set to true to show the BusyIndicator. Here is the whole implementation of the CustomerViewModel:

  public class CustomerViewModel : ViewModel, ISaveableViewModel
  {
        CustomerContext _customerContext = new CustomerContext();
        CustomerDto _customerDto = new CustomerDto();

        bool _isLoading = false;

        public CustomerViewModel()
        {
            this.IsLoading = true;

            _customerContext.Load<CustomerDto>(
_customerContext.GetCustomerByIDQuery(10), loadOperation => { _customerDto = loadOperation.Entities.SingleOrDefault(); LoadingCompleted(); }, null); } public string FirstName { get { return _customerDto.FirstName; } set { if (_customerDto.FirstName != value) { _customerDto.FirstName = value; NotifyPropertyChanged("FirstName"); } } } public string LastName { get { return _customerDto.LastName; } set { if (_customerDto.LastName != value) { _customerDto.LastName = value; NotifyPropertyChanged("LastName"); } } } public bool IsLoading { get { return _isLoading; } internal set
{
_isLoading = value;
NotifyPropertyChanged("IsLoading");
            }
        }

        
        public bool IsAdult
        {
            get { return _customerDto.Age >= 18; }
        }


        public ICommand Save
        {
            get { return new SaveCommand(this); }
        }


        internal void SaveCustomer()
        {
            _customerContext.SubmitChanges();
        }






private void LoadingCompleted()
{
NotifyPropertyChanged("FirstName");
NotifyPropertyChanged("LastName");
NotifyPropertyChanged("IsAdult");
this.IsLoading = false;
} }

Note: The above CustomerViewModel is not designed for testability, if we want to write a unit test to test the ViewModel, we could for example pass a DomainClient to the CustomerContext constructor when it’s created, it can be done in several ways, one way is for example to pass the DomainClient as an argument to the CustomerViewModel constructor, but then we have to use code-behind to create the CustomerViewModel or adding our own AttachedProperty. We can also add a DomainClient as a resources in XAML and use property injection to inject the DominContext to the ViewModel.

Something that may seems strange is the empty CustomerDto assigned to the _customerDto field. The other properties in the CustomerViewModel will access the _customerDto and its properties. To avoid adding a lot of if statements to check for null in both the get and set, a default CustomerDto is used. So it’s only a “ugly” hack to avoid a lot of code in each property. The load operation of a Customer will take place in the default constructor of the CustomerViewModel:

public CustomerViewModel()
{
   this.IsLoading = true;

   _customerContext.Load<CustomerDto>(
             _customerContext.GetCustomerByIDQuery(10),
             loadOperation =>
             {
                  _customerDto = loadOperation.Entities.SingleOrDefault();
                  LoadingCompleted();
             }, null);
}


The IsLoading property is set to true to make sure the BusyIndicator will be displayed when the loading takes place. When the loading of the Customer is completed the _customerDto will be set to the loaded customer and the LoadingCompleted method will be called. This method will make sure the BusyIndicator will be hidden and also notify the View about changes, so the bindings to the controls will call the get methods of bounded properties to get the loaded customer’s information and show it. The last part to cover is the use of Commanding in Silverlight 4.

Commanding

You can read about Commanding in my post “Silverlight 4 Commanding enables ViewModels”. In the ViewModel there are one method SaveRule, this is from the interface ISaveableViewModel implemented by the CustomerViewModel. There is also a Save property added to the CustomerViewModel, this property will return a SaveCommand where the ViewModel is passed as an argument.

public ICommand Save
{
    get { return new SaveCommand(this); }
}

internal void SaveRule()
{
     _customerContext.SubmitChanges();
}

The Save property is bounded to the View’s Save button’s command property. Here is the implementation of the SaveCommand returned from the Save property:

public class SaveCommand : ICommand
{
    private ISaveableViewModel _view;

    public SaveCommand(ISaveableViewModel view)
    {
        _view = view;
    }

    public bool CanExecute(object parameter)
    {
       return true;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        _view.SaveRule();
     }
}


As you can see the SaveCommand takes a ISaveableViewModel interface (Yes I know the name of the interface may be strange, but I’m not so good at naming ;)). The idea is to make sure the operation the Command should execute is added to the ViewModel itself, by doing so the Command can be reused by several other Views.

Summary

This post was about giving you the ideas of how you can use WCF RIA Services, the Model View View Model pattern and Commanding. The code used in this example is not perfect, no specific error handling was added more than using the WCF RIA Services validation annotation.

If you want to know when I publish a new blog post, then follow me on twitter: http://www.twitter.com/fredrikn

Published Monday, November 30, 2009 7:38 PM by Fredrik N

Comments

# Twitter Trackbacks for Silverlight 4 - MVVM with Commanding and WCF RIA Services - Fredrik Norm??n [asp.net] on Topsy.com

Pingback from  Twitter Trackbacks for                 Silverlight 4 - MVVM with Commanding and WCF RIA Services - Fredrik Norm??n         [asp.net]        on Topsy.com

# Dew Drop &#8211; December 1, 2009 | Alvin Ashcraft&#039;s Morning Dew

Tuesday, December 01, 2009 8:02 AM by Dew Drop – December 1, 2009 | Alvin Ashcraft's Morning Dew

Pingback from  Dew Drop &#8211; December 1, 2009 | Alvin Ashcraft&#039;s Morning Dew

# re: Silverlight 4 - MVVM with Commanding and WCF RIA Services

Monday, December 14, 2009 4:58 AM by ManuelFelicio

Hi,

Why dont you have your commands depend on Action and Func delegates instead of interfaces? That way reduces a lot your codebase and your commands will be a lot more reusable.

One question: how would you return a IQueryable<CustomerDto> ? Is the RIA Services presentation model available for .NET 3.5?

Thanks,

MF.

# links for 2009-12-16

Wednesday, December 16, 2009 4:05 PM by SKOROZSI.NET

links for 2009-12-16

# re: Silverlight 4 - MVVM with Commanding and WCF RIA Services

Monday, December 21, 2009 5:04 PM by Peter

Hi,

Thanks for the great post. I have already learned a lot from what I have read so far. Do you have a sample app or some code I could play with??

Thanks!

# #Silverlight: MVVM RIA http://weblogs.asp.net/fredriknormen/archive/2009/11/30/silverlight-4-mvvm-with-commanding-and-wcf-ria-services.aspx

Monday, December 28, 2009 10:08 AM by Twitter Mirror

#Silverlight : MVVM RIA http://weblogs. asp.net /fredriknormen/archive/2009/11/30/silverlight-4-mvvm

# re: Silverlight 4 - MVVM with Commanding and WCF RIA Services

Wednesday, January 13, 2010 1:39 PM by Tolga

Can you please show code for

"MapCustomerDtoToCustomer"

# re: Silverlight 4 - MVVM with Commanding and WCF RIA Services

Thursday, January 14, 2010 2:33 PM by Jonathan

I nice intro article into MVVM but for real world applications, you have many views and you need an effective way of loading your views. In WPF you could just have DataTemplates with the DataType property.  WPF could automatically load your DataTemplate for you.  There is no such feature in Silverlight 4 and I am wondering if someone has an elegant solution to switching between views?

# SL4 with MVVM saved me http://weblogs.asp.net/fredriknormen/archive/2009/11/30/silverlight-4-mvvm-with-commanding-and-wcf-ria-services.aspx

Friday, January 22, 2010 4:31 AM by Twitter Mirror

SL4 with MVVM saved me http://weblogs. asp.net /fredriknormen/archive/2009/11/30/silverlight-4-mvvm-with

# re: Silverlight 4 - MVVM with Commanding and WCF RIA Services

Friday, January 22, 2010 6:36 AM by Florin

Hi Fredrik.

Is load balancing supported by RIA Services?

# re: Silverlight 4 - MVVM with Commanding and WCF RIA Services

Monday, February 22, 2010 11:37 PM by Azadeh

Hi Fred,

Very Useful Post , Thanks a lot.

But any chance to see the code sample , please?

Thanks,

# re: Silverlight 4 - MVVM with Commanding and WCF RIA Services

Wednesday, June 30, 2010 4:09 AM by Jacques

Thank you very much for the concise & very informing article, that cuts through the clutter & clearly demonstrates the essence of MVVM & RIA Services in a few short paragraphs.

# re: Silverlight 4 - MVVM with Commanding and WCF RIA Services

Friday, August 20, 2010 12:57 PM by Mia

When I injected my dependency into my service class (and wired it in the global.asax), my ViewModel can neither reference the DomainContext nor the DTO objects.  Any ideas?

# re: Silverlight 4 - MVVM with Commanding and WCF RIA Services

Tuesday, September 14, 2010 8:33 PM by sri

Hi Fred,

Can I get a chance to see the code for CustomerRepository

# re: Silverlight 4 - MVVM with Commanding and WCF RIA Services

Wednesday, September 15, 2010 12:22 AM by srinivas

Hi Fred,

Please share the code.

# re: Silverlight 4 - MVVM with Commanding and WCF RIA Services

Thursday, September 16, 2010 3:58 PM by srinivas

can we see complete code

# re: Silverlight 4 - MVVM with Commanding and WCF RIA Services

Friday, September 17, 2010 5:52 PM by vsgoud

Nice post. It is very clear and precise.

Do you have a code for CustomerRepository using Entity framework?

can you send the code to vsgoud@hotmail.com

# The Player Map | the Grindstone Developers Blog

Monday, October 03, 2011 8:09 AM by The Player Map | the Grindstone Developers Blog

Pingback from  The Player Map | the Grindstone Developers Blog

# The Game Map | The GORMS Dev Blog

Tuesday, October 04, 2011 1:20 AM by The Game Map | The GORMS Dev Blog

Pingback from  The Game Map | The GORMS Dev Blog

Leave a Comment

(required) 
(required) 
(optional)
(required)