MVVM Architecture When Using Web Services For Database Interaction

In regular MVVM pattern, Model handles data and other database functions. But, if we do not want our application to directly communicate to the database but rather via Web Service, then all the responsibilities of Model need to be transferred to web service and we do not give the service reference directly to the main project to use the web service.

We need to create different projects for this work. Let's understand the architecture for the same.



Step 1

Let's create one WPF project, as shown in the above screenshot.

Step 2

Views (Windows and User controls) need to be added in this main project.



Step 3

Add another C# library project to the solution. I named it as WebService.
Add the reference of your service to this project (See the snapshots for better understanding).



Step 4

Add another C# library project to the Solution that will be ‘ViewModels’ and add the reference of Service project to Main project and ViewModel project.

Add the reference of ViewModel project to Main project.




So, this was all about how to manage the architecture. Now, let's see a little about how this pattern will work and follow the MVVM along with how the "PropertyChanged" nofications and event notifications will work.
  1. Add a window under Views folder in Main project.

    Now, we have added three textboxes to fill the details for an organization - Name, Username, and Password.



  2. Each View must have corresponding ViewModel. So, let's add ViewModel for company details.

    As we know, we need PropertyChanged notification events, InotifyPropertyChanged needs to be written for each ViewModel properties. Commands to handle click events also need to be written for each ViewModel.

    So, we should create a common layer that will contain all these common things and we can directly access or reference them wherever we need. So, let's pass a CommonLayer.

Add class named as "BaseViewModel" that consists of all InotifyPropertyChanged for properties.

  1. namespace CommonClasses {  
  2.     public class BaseViewModel   
  3. {  
  4. #region INotifyPropertyChanged Members  
  5.         /// <summary>  
  6.         /// Raises the PropertyChange event for the property specified  
  7.         /// </summary>  
  8.         /// <param name="propertyName">Property name to update. Is case-sensitive.</param>  
  9.         public virtual void RaisePropertyChanged(string propertyName) {  
  10.             OnPropertyChanged(propertyName);  
  11.         }  
  12.         /// <summary>  
  13.         /// Raised when a property on this object has a new value.  
  14.         /// </summary>  
  15.         public event PropertyChangedEventHandler PropertyChanged;  
  16.         /// <summary>  
  17.         /// Raises this object's PropertyChanged event.  
  18.         /// </summary>  
  19.         /// <param name="propertyName">The property that has a new value.</param>  
  20.         protected virtual void OnPropertyChanged(string propertyName) {  
  21.             PropertyChangedEventHandler handler = this.PropertyChanged;  
  22.             if (handler != null) {  
  23.                 var e = new PropertyChangedEventArgs(propertyName);  
  24.                 handler(this, e);  
  25.             }  
  26.         }#endregion // INotifyPropertyChanged Members  
  27.     }  
  28. }  

 The above code shows that we have created the PropertyChanged event notifications independent of any ViewModel or any property. So, we can easily differentiate between the different Views and ViewModel properties on the basis of some token GUID variable. We will be discussing that in the next article when we will create a sample application.

Let's concentrate only on the architecture for this article.
 
Let's see what we need to do for Click Event Commands in CommonClass.
  1. namespace CommonClasses {  
  2.     public class CommandClass: ICommand {  
  3.     #region Fields  
  4.         readonly Action < object > _execute;  
  5.         readonly Predicate < object > _canExecute;  
  6.         #endregion // Fields  
  7.         # region Constructors  
  8.         /// <summary>  
  9.         /// Creates a new command that can always execute.  
  10.         /// </summary>  
  11.         /// <param name="execute">The execution logic.</param>  
  12.         public CommandClass(Action < object > execute): this(execute, null) {}  
  13.         /// <summary>  
  14.         /// Creates a new command.  
  15.         /// </summary>  
  16.         /// <param name="execute">The execution logic.</param>  
  17.         /// <param name="canExecute">The execution status logic.</param>  
  18.         public CommandClass(Action < object > execute, Predicate < object > canExecute) {  
  19.             if (execute == nullthrow new ArgumentNullException("execute");  
  20.             _execute = execute;  
  21.             _canExecute = canExecute;  
  22.         }  
  23.         #endregion // Constructors  
  24.         # region ICommand Members[DebuggerStepThrough]  
  25.         public bool CanExecute(object parameter) {  
  26.             return _canExecute == null ? true : _canExecute(parameter);  
  27.         }  
  28.         public event EventHandler CanExecuteChanged {  
  29.             add {  
  30.                 CommandManager.RequerySuggested += value;  
  31.             }  
  32.             remove {  
  33.                 CommandManager.RequerySuggested -= value;  
  34.             }  
  35.         }  
  36.         public void Execute(object parameter) {  
  37.             _execute(parameter);  
  38.         }#endregion // ICommand Members  
  39.     }  
  40.     public class CommandClass < T > : ICommand {  
  41.         private Action < T > methodToExecute;  
  42.         private Func < T, bool > canExecuteEvaluator;  
  43.         public event EventHandler CanExecuteChanged {  
  44.             add {  
  45.                 CommandManager.RequerySuggested += value;  
  46.             }  
  47.             remove {  
  48.                 CommandManager.RequerySuggested -= value;  
  49.             }  
  50.         }  
  51.         public CommandClass(Action < T > methodToExecute, Func < T, bool > canExecuteEvaluator) {  
  52.             this.methodToExecute = methodToExecute;  
  53.             this.canExecuteEvaluator = canExecuteEvaluator;  
  54.         }  
  55.         public CommandClass(Action < T > methodToExecute): this(methodToExecute, null) {}  
  56.         private bool CanExecute(T parameter) {  
  57.             if (this.canExecuteEvaluator == nullreturn true;  
  58.             return this.canExecuteEvaluator.Invoke(parameter);  
  59.         }  
  60.         private void Execute(T parameter) {  
  61.             this.methodToExecute.Invoke(parameter);  
  62.         }  
  63.         public bool CanExecute(object parameter) {  
  64.             return this.CanExecute((T) parameter);  
  65.         }  
  66.         public void Execute(object parameter) {  
  67.             this.Execute((T) parameter);  
  68.         }  
  69.     }  
  70. }  

The above common code needs to be written in command Common Class.

Now, let's see how to use reference of the above two classes in ViewModel.

  1. Add reference of CommonClass project to ViewModel project.
  2. Inherit the common class BaseViewModel.
    1. namespace ViewModels  
    2. {  
    3. public class CompanyDetailsViewModel:BaseViewModel  
    4. {  
    5. }  
    6. }  

That's it.