WPF and MVVM tutorial 07, the List search.

Add Comment | Jul 03, 2009

Ok, starting from this post we are going to do something really interesting. In this episode we need to create a simple List windows, but as you will see the logic will not be so different then a one-to-many form.

This will be the final result:

image

The ViewModel for the List Window.

First of all we need to create the view model. The view model should have the following commands:

  1. New – Add a new Customer
  2. Save – Save all the changes we did …
  3. Edit – Edit the current selected customer
  4. Delete – Delete the current selected customer
  5. Text box and search button – to operate search activity
  6. Exit the form

Then we need to add the following objects:

  1. An observable collection for the list of customers
  2. A current customer object, but this is not mandatory …
  3. The search information we retrieve from the view, or better, the view sends to us.

The final result will be this view model class:

image

Let’s have a look at the View Model commands. As you know when we assign a RelayCommand, we can do it in 2 ways:

By passing with a lambda expression the corresponding action.

By passing with a lambda expression the corresponding action and a predicate (something like true/false).

So for some commands like Save or Delete we can also build a predicate action like CanSave? CanDelete? and encapsulating some validation logic inside.

So the code should look like:

 

The RelayCommands.

Simple command like Create a new customer:

  1: //Private field
  2: public ViewCommand newCommand;
  3: //Public property to be assigned in the XAML code
  4: public ViewCommand NewCommand {
  5:    get {
  6:       if (newCommand == null)
  7:          newCommand = 
  8:          //Lambda expression for assigning the action
  9:          new ViewCommand(param => this.NewCustomer());
 10:       return newCommand;
 11:    }
 12: }
 13: //Real routine executed in the ViewModel
 14: private void NewCustomer() {
 15:    NavigationActions.OpenCustomerView();
 16: }
 17: 

Or something more complex like Delete a customer:

  1: //Private command field
  2: private ViewCommand deleteCommand;
  3: //Public databinded ICommand
  4: public ViewCommand DeleteCommand {
  5:    get {
  6:       if (deleteCommand == null) {
  7:       deleteCommand = new ViewCommand(
  8:           param=>this.DeleteCustomer(),
  9:           //Lambda expression for evaluating the execution
 10:           param=>this.CanDeleteCustomer
 11:           );
 12:       }   
 13:       return deleteCommand;
 14:    }
 15: }
 16: //Real delete command
 17: public void DeleteCustomer() {
 18:    if (SelectedCustomer != null) {
 19:       if(NavigationActions.QueryConfirmation(
 20:          "Delete Customer.",
 21:          string.Format("Do you want to delete {0}?",SelectedCustomer.FirstName))){
 22:          ListOfCustomers.Remove(SelectedCustomer);
 23:          repository.DeleteCustomer(SelectedCustomer);
 24:       }
 25:    } else {
 26:       NavigationActions.ShowError(
 27:         "Delete Customer.", 
 28:         "You must select a Customer!");
 29:    }
 30: }
 31: //Additional logic can go here ...
 32: private bool CanDeleteCustomer {
 33:    get { return true; }
 34: }
 35: 

Then of course we will have two different command for Edit a Customer or create a new one, and at the end the difference will be just here:

  1: //Open the Customer window empty
  2: NavigationActions.OpenCustomerView();

  4: NavigationActions.OpenCustomerView(SelectedCustomer);
  3: //Open the Customer window passing a Customer
  5: 
  6: 

The others commands are the same, but if you want in my solution you can find the complete implementation.

Loading and working with a Collection.

After we build all the commands and we bind them to the XAML code, we need to load our entities. For this we will use a ObservableCollection List that we will implement in the initialization of our View Model, so when the Window will open we will also load the Collection inside the ListView.

  1: //We need an instance of our repository
  2: CustomerRepository repository;
  3: //This will contain our Customers
  4: ObservableCollection<Customer> listOfCustomers;
  5: //This will be the current selected customer
  6: Customer selectedCustomer;
  7: public CustomersViewModel() {
  8:    if (repository == null) {
  9:       //Initialization of the Repository
 10:       repository = new CustomerRepository();
 11:    }
 12:    Initialization of the List
 13:    listOfCustomers = 
 14:       new ObservableCollection<Customer>(
 15:          repository.GetAllCustomers());
 16:    this.SearchText = "Some text to search ...";
 17: }
 18: //Binded property containing the Customer list
 19: public ObservableCollection<Customer> ListOfCustomers {
 20:    get { return listOfCustomers; }
 21: }
 22: 

INotifyPropertyChanged

If we want to advise the UI that we loaded a new customers list, we have to build a ViewModel that implements the INotifyPropertyChanged in this way:

  1: #region INotifyPropertyChanged Members
  2: 
  3: public event PropertyChangedEventHandler PropertyChanged;
  4: 
  5: public void NotifyPropertyChanged(String info) {
  6:    if (PropertyChanged != null) {
  7:       PropertyChanged(
  8:          this, 
  9:          new PropertyChangedEventArgs(info)
 10:       );
 11:    }
 12: }
 13: 
 14: #endregion

And then change the property code in this way:

  1: public ObservableCollection<Customer> ListOfCustomers {
  2:     
  3:     get { return listOfCustomers; }
  4:     private set {
  5:         if (listOfCustomers != value) {
  6:             listOfCustomers = value;
  7:             NotifyPropertyChanged("ListOfCustomers");
  8:         }
  9:     }
 10: }

Now, everytime we are going to load something new into the collection, or we are going to use a view of the collection the ViewModel will send a message in the view saying “Hey, look I changed something in the list, update the UI!!”.

Some XAML code.

Now we have the Commands, the Model and we need to bind them to the view.

Loading the viewmodel into the view:

  1: ...
  2: <xmlns:vm=
  3:    "clr-namespace:MVVM.ViewModel;
  4:    assembly=MVVM.ViewModel />
  5: 
  6: ...
  7: <Window.DataContext>
  8:    <vm:CustomersViewModel/>
  9: </Window.DataContext>

Binding one command to a Button:

  1: <Button Name="btnNew" Command="{Binding Path = NewCommand}">

Binding the List to the ListView and assigning the selected customer:

  1: <ListView 
  2:   Name="lstCustomers" 
  3:   ItemsSource="{Binding Path=ListOfCustomers}"
  4:   SelectedItem="{Binding Path=SelectedCustomer}" 
  5:   SelectionMode="Single"
  6:   IsSynchronizedWithCurrentItem="True"
  7:   HorizontalAlignment="Stretch" 
  8:   VerticalAlignment="Stretch"
  9:   MinHeight="100">

The IsSynchronizedWithCurrentItem bind the listview and the selecteditem together.

Now, what we should be able to do here is to Load the customers, press delete and wipe one or more then one. Then:

  1. If we close the window and we reopen it the Customer will re-appear again.
  2. If we commit all the changes with the SaveCommand and the we close and re-open the window, the Customer will not be there anymore.

In this lesson we will see only how to implement the search function. In the next one we will see each single command in details.

The user types some text and after that he searches for a result.

  1: private void FindCustomers() {
  2:    //If there is no text, prompt an error
  3:    //In the future this will be a XAML trigger
  4:     if (this.SearchText == string.Empty || this.SearchText == null) {
  5:         NavigationActions.ShowError("Search Customers.", "Please enter some text ...");
  6:         return;
  7:     }
  8:    //Keep the search text and build a dynamic query for the DAL
  9:     ListOfCustomers = new ObservableCollection<Customer>(
 10:         repository.GetCustomersByQuery(
 11:         p => p.CompanyName.StartsWith(SearchText)
 12:         || p.FirstName.StartsWith(SearchText)
 13:         || p.LastName.StartsWith(SearchText)));
 14: }
 15: 

At this point we will have a first final search solution like these screenshots:

image image

 

 

 

 

 

Tags:

WPF and MVVM tutorial 06, start up form.

2 Comments | Jun 17, 2009

Today we are going to create the start-up form of our project and use the first ViewModel to run the application logic.

The result we want to obtain will be:

image

The View Model for the Startup form.

In our project, let’s go to the ViewModel section and create a new class. This class will inherit from the basic View Model class like the code below:

  1: public class StartViewModel : ViewModel {
  2: 
  3:    public StartViewModel() {
  4: 
  5:    }
  6: }

Then we need to create 2 commands that we will then associate to two buttons in our XAML form. One will start the application and one will shut-down the application.

This is the implementation we need to do in our ViewModel in order to create the Relay Command:

  1: public ViewCommand startCommand;
  2: public ViewCommand StartCommand {
  3:     get {
  4:         if (startCommand == null)
  5:             startCommand = new ViewCommand
  6:                  (param => this.StartApplication());
  7:         return startCommand;
  8:     }
  9: }
 10: 

Then we need a delegate for the relay command in this way:

  1: private void StartApplication() {
  2:   NavigationActions.OpenCustomersView();
  3: }
  4: 

The first XAML Form of our Application.

I am not a guru in windows design, especially the fancy UI but the final project will have a startup form like this one:

image

First of all add a new XAML form into the UI layer and then let’s see at the XAML code:

  1: <Window x:Class="MVVM.WPFView.Start"
  2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4:     xmlns:vm="clr-namespace:MVVM.ViewModel;assembly=MVVM.ViewModel"
  5:         Title="MVVM AdventureWorks Application." 
  6:         Height="500" Width="500"
  7:         WindowStartupLocation="CenterScreen" WindowState="Normal"
  8:         WindowStyle="None">
  9: 

If you look at the line 4, we added a reference to our viewmodel namespace. In this way we can use in a declarative way the objects in the viewmodel namespace, directly into XAML (I personally hate to use procedural code into XAML!)

  1:     <Window.DataContext>
  2:         <vm:StartViewModel />
  3:     </Window.DataContext>
  4: 

Then we add as a resource, the StartViewModel view model into our Window. In this way when the window will load the XAML declaration will inform the CLR to load a default instance of our view model.

Now let’s view the two buttons:

  1: <Button Name="btnStart" Margin="5" 
  2: IsDefault="True" 
  3: Command="{Binding Path=StartCommand}">

The binding will be the Relay Command we have previously created in the View model class. Easy right?

Now, the next step will be to build the View model to show all the customers. Then we will build some specific command for the C.R.U.D. operations.

Stay tuned!

Tags:

WPF and MVVM tutorial 05, The basic ViewModel.

Add Comment | Jun 16, 2009

As we saw in the previous posts, a view model should be an abstract implementation of what the view needs to show about the model. We should implement an observable collection of something, we should implement an INotifyPropertyChanged interface and we should have a collection of RelayCommands.

For these reasons, it simply to understand that we need a basic abstract ViewModel class, just to recycle some code.

image

The Basic View Model.

  1: namespace MVVM.ViewModel {
  2:     public abstract class ViewModel:INotifyPropertyChanged,IDisposable {
  3: 
  4:         INavigationActions navigator;
  5: 
  6:         public ViewModel() {
  7:             navigator = Application.Current as INavigationActions;
  8:             if (navigator != null) {
  9:                 navigator.PropertyChanged += application_PropertyChanged;
 10:             }
 11:         }
 12: 
 13:         void application_PropertyChanged(object sender, PropertyChangedEventArgs e) {
 14:             if (string.IsNullOrEmpty(e.PropertyName) || e.PropertyName == "View")
 15:                 OnPropertyChanged("View");
 16:         }
 17: 
 18:         public INavigationActions NavigationActions {
 19:             get {
 20:                 return navigator;
 21:             }
 22:             set {
 23:                 if (navigator != value) {
 24:                     SetAction(value);
 25:                     OnPropertyChanged("NavigationActions");
 26:                 }
 27:             }
 28:         }
 29: 
 30:         protected virtual void SetAction(INavigationActions value) {
 31:             if (navigator != null)
 32:                 navigator.PropertyChanged -= application_PropertyChanged;
 33:             navigator = value;
 34:             if (navigator != null)
 35:                 navigator.PropertyChanged += application_PropertyChanged;
 36:         }
 37: 
 38:         #region INotifyPropertyChanged Members
 39:         /// <summary>
 40:         /// Raised when a property has a new value
 41:         /// </summary>
 42:         public event PropertyChangedEventHandler PropertyChanged;
 43:         /// <summary>
 44:         /// Raise the event
 45:         /// </summary>
 46:         /// <param name="propertyName">Property name that has new value</param>
 47:         protected virtual void OnPropertyChanged(string propertyName) {
 48:             PropertyChangedEventHandler handler = this.PropertyChanged;
 49:             if (handler != null) {
 50:                 var e = new PropertyChangedEventArgs(propertyName);
 51:                 handler(this, e);
 52:             }
 53:         }
 54:         #endregion
 55: 
 56:         #region IDisposable Members
 57:         /// <summary>
 58:         /// Implementation of the dispose method
 59:         /// </summary>
 60:         public void Dispose() {
 61:             this.OnDispose();
 62:         }
 63:         /// <summary>
 64:         /// The child class should implement a personal dispose procedure
 65:         /// </summary>
 66:         protected virtual void OnDispose() {
 67:             //do nothing because abstract
 68:         }
 69: 
 70:         #endregion
 71:     }
 72: }

A small summary of our code:

  1. An implementation of the INotifyPropertyChanged that we can use in the concrete views.
  2. An implementation of the IDisposable in order to clean our objects like collections and repositories.
  3. An INavigator interface to implement the navigation of our application. In this case I am using the navigator pattern for composite WPF applications. Beware because this is my implementation for the navigation but it depends on how you design your app (multi-win, tab, MDI).

The INavigator implementation.

The are thousands of ways to implement a navigator engine. The only common purpose in MVVM is that the View Model doesn’t know the View but the View knows the View Model. So in our example which part of the View can interact with the application and doesn’t need to know the View Model? The app.xaml file!

My idea is this one:

image

We will have a simple interface in the ViewModel namespace which will identify the navigation commands we want to execute:

  1: public interface INavigationActions:INotifyPropertyChanged 
  2: {
  3:     void OpenCustomersView();
  4:     void OpenCustomerView();
  5:     void OpenOrdersView();
  6:     void OpenOrderView();
  7:     void CloseCurrentView();
  8:     void CloseApplication();
  9:     bool QueryConfirmation(string title, string message);
 10:     void ShowError(string title, string message);
 11: }

In this way we can call everything from our viewmodel that doesn’t know the view.

Now we just need to implement the view in the Application file in this way:

  1: public partial class App : Application,INavigationActions,INotifyPropertyChanged {
  2:     #region INavigationActions Members
  3: 
  4:     public void OpenCustomersView() {
  5:         CustomersView customersView = new CustomersView();
  6:         customersView.Show();
  7:     }
  8: 
  9:     public void OpenCustomerView() {
 10: 
 11:     }
 12: 
 13:     public void OpenOrdersView() {
 14: 
 15:     }
 16: 
 17:     public void OpenOrderView() {
 18: 
 19:     }
 20: 
 21:     public void CloseCurrentView() {
 22: 
 23:     }
 24: 
 25:     public void CloseApplication() {
 26:         Application.Current.Shutdown();
 27:     }
 28: 
 29:     public bool QueryConfirmation(string title, string message) {
 30:         return MessageBox.Show(title, message, MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes;
 31:     }
 32: 
 33:     public void ShowError(string title, string message) {
 34:         MessageBox.Show(title, message, MessageBoxButton.YesNo, MessageBoxImage.Error);
 35:     }

And there we go!!

Ops I forgot to mention that in the basic View Model we need to handle the INavigation

  1: public ViewModel() {
  2:     navigator = Application.Current as INavigationActions;
  3:     if (navigator != null) {
  4:         navigator.PropertyChanged 
  5:         += application_PropertyChanged;
  6:     }
  7: }
  8: 

For the rest you need to wait the next tutorial!!

Tags:

WPF and MVVM tutorial 04, The Commands.

Add Comment | Jun 15, 2009

In the previous posts we saw the basic of our project, the model (domain entities) and a simple repository.

Note: please note that the sample I wrote about an agnostic UnitOfWork is just to show you a simple pattern to handle L2S but it can be done better.

The ViewModel.

What is the view model? Well the simplest explanation is enclosed in this definition: the view model should be the datacontext of our view. It should provide the commands, the observable collections used in the view and the error logic.

Before starting to view how to build the basic abstract class for the viewmodel I want to talk about the Relay Command and the Routed Command and their differences.

Routed or Relay command?

I have found a useful explanation here, in the Josh Smith blog. Routed events are events designed to work in a tree of elements. When a user click the text over a button, the even travels over the tree until it will find the Click event of the chrome button.  This is how a button implements a routed events:

  1: public class Button:ButtonBase
  2: {
  3:    static Button()
  4:    {
  5:       Button.ClickEvent = EventManager.RegistedRoutedEvent
  6:          ("Click", RoutingStrategy.Bubble,
  7:           typeof(RoutedEventHandler), typeof(Button));
  8:    }
  9:    public RoutedEventHandler Click
 10:    {
 11:       add { AddHandler(Button.ClickEvent,value); }
 12:       remove { RemoveHandler(Button.ClickEvent,value); }
 13:    }
 14:    protected override void 
 15:       OnMouseLeftButtonDown(MouseButtonEventArgs e){
 16:       RaiseEvent(new RoutedEventArgs(Button.ClickEvent,this);
 17:    }
 18: }

The commands in WPF represent a more independent action from their user interface. Also WPF and NET expose a default set of commands that we can easily handle in our application, like:

Application command, ComponentCommand, MediaCommand, NavigationCommand and EditingCommand.

They inherit all, from the ICommand interface. So for each command you want to implement, it should inherit from ICommand in this way:

  1: #region ICommand Members
  2: 
  3: public bool CanExecute(object parameter) {
  4:     return _canExecute == null ? true : _canExecute(parameter);
  5: }
  6: 
  7: public event EventHandler CanExecuteChanged {
  8:     add { CommandManager.RequerySuggested += value; }
  9:     remove { CommandManager.RequerySuggested -= value; }
 10: }
 11: 
 12: public void Execute(object parameter) {
 13:     _execute(parameter);
 14: }
 15: 
 16: #endregion

So it becomes simple to understand that we should have a View Model abstract class that contains an abstract implementation of a collection of ICommand. Then we can inherits each view model from this one!

So our conclusion is that:

The key difference is that RoutedCommand is an ICommand implementation that uses a RoutedEvent to route through the tree until a CommandBinding for the command is found, while RelayCommand does no routing and instead directly executes some delegate. In a M-V-VM scenario a RelayCommand (DelegateCommand in Prism) is probably the better choice all around.

The final implementation of the Relay command should be something like:

image

In the next tutorial we will see how to build the abstract layer for a basic view model with a basic collection of relay commands.

Tags:

Technorati test.

Add Comment | Jun 11, 2009

kyrprtqfs9

Technorati Profile

WPF and MVVM tutorial 03, The user repository.

2 Comments | Jun 05, 2009

Before starting to view in depth our model, or to design the views, I want to complete the DAL layer. Now that we have our unit of work implementation and our data context we need to implement a couple of repositories.

If you want to view how it should work a repository, I suggest this interesting article from Martin Fowler. The presenter should be:

A Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection.

The Flow of our application.

During the time I saw different repositories. One for each entity, one for each View and so on. My approach, usually, is to use a relationship of 1-to-1 from the view and the repository. So in our case we will have:

image 1 - The user opens the program and has to decide (search a customer, view all customers)

2 – A list will be presented to the user (filtered or not) and he will have to select one customer.

3 – A third view will show the details of the user, with two sub-view (address and order details).

So this is the flow that we will follow. For these reasons, you will easily understand that we need a couple of repositories: A) a user repository, B) an order repository.

 

The User repository.

The user repository has to give us a way to execute any kind of CRUD operation against our database. So we should have something like:

image

Here there are some basic operations we must be able to accomplish with our repository.

1) Get a specific Customer or Get all of them.

2) Add, Update or Drop a Customer.

3)Commit the changes to the data-model.

 

 

The code is very simple. First of all we need to create a sealed repository, so that nobody will play with it, for this purpose there is the IUnitOfWOrk interface …

  1: public sealed class CustomerRepository {
  2:     //Create an istance (it's static) of our Unit of Work
  3:     private IUnitOfWork _service;
  4:     //but let's give it a read-only access
  5:     public IUnitOfWork Service {
  6:         get { return _service; }
  7:     }
  8:     //create a new istance of the Unit of work
  9:     public CustomerRepository() {
 10:         _service = new UnitOfWork();
 11:     }
 12: 

Then we need to implement the custom methods to retrieve the information we need from our model. Fortunately we have a generic unit of work so the code behind it’s very very simple!

  1: //Add a new customer
  2: public void AddCustomer(Customer _customer) {
  3:     Service.Add<Customer>(_customer);
  4: }
  5: //Drop an existing one
  6: public void DeleteCustomer(Customer _customer) {
  7:     Service.Delete<Customer>(_customer);
  8: }
  9: //Update an existing dirty customer
 10: public void UpdateCustomer(Customer _customer) {
 11:     Service.Update<Customer>(_customer);
 12: }
 13: Get a specific customer
 14: public Customer GetCustomer(int id) {
 15:     return Service.GetById<Customer>(p => p.CustomerID == id);
 16: }
 17: //Get all of them
 18: public IList<Customer> GetAllCustomers() {
 19:     return Service.GetAll<Customer>();
 20: }

We should also implement a filtered GetAllCustomers but we will use the View Model to do that in our example.

Customer class diagram.

Now we are pretty fine with our Customer model. What we have know is a model, a repository and a CRUD implementation for the customer and the related entities (Address and so on …). The final result in our DAL layer is this one:

image

Great we can already build now 3 views (CustomersView, CustomerView, FilteredCustomersView) just by using one repository. TO be honest we should be able to do everything but I want to keep separate the Order section.

In the next step I will give an overview of the ViewModel, and the View interaction, then we will start to build the views and then the relative ViewModels.

Ndr. I saw that this series of articles is being read by a nice number of people. Please post any ideas, suggestion or whatever you think about … I will appreciate.

Tags:

WPF and MVVM tutorial 02, The model.

One Comment | Jun 05, 2009

In the first part of this tutorial we saw the MVVM model and how it works.

In this part of our tutorial we will work directly with the Entity Model and LinqToSQL. I am using a database-first approach so in my opinion using LinqToSQL will be better then Entitiy Framework. I am going also to show you an easy way to build a custom Unit Of Work to manage the context status with Linq 2 SQL.

The Visual Studio Project.

First of all open a blank Visual Studio solution, I called it WPF.Tutorial.VMMV. Add two projects on it: 1) WPF Application …UI and 2) Class Library (…DAL).

The final layout should be this one (in my picture the model is already inside).

New Picture (8)

The Data model.

If you have installed the Adventure Works database in the past you already know what I am talking about. The model I will use in the tutorial will come up with this layout:

New Picture (7)We will have a customer with the personal information and the related orders with the order information.

Go into the DAL project and from the menu choose add new file –> LinqToSQL and call it DataModel. Now you need to connect you data model into your AW database and drag in the design pane the tables you need. At the end you should come up with the same layout I have in the previous picture.

The Unit of Work.

If you do not what I am talking about, this is the explanation by Martin Fowler.

A Unit of Work keeps track of everything you do during a business transaction that can affect the database. When you're done, it figures out everything that needs to be done to alter the database as a result of your work.

Of course with LinqToSQL we do not need a Unit of Work because L2S by itself is the data context, but because it is not able to manage the disposing in a good way, here are my 2 cents about.

We need a contract, in this way an interface in the DAL that will implement the Unit of Work:

image

First of all let’s build the C.R.U.D. implementation into a simple interface. In this case I am going to use the generics and the Linq expression because my project will work only with Linq so I do not need an high level of abstraction:

  1: using System;
  2: using System.Collections.Generic;
  3: 
  4: namespace WPF.Tutorials.VMMV.DAL {
  5:     public interface IUnitOfWork {
  6:         //Basic C.R.U.D. operations
  7:         void Add<T>(T _entity) where T : class;
  8:         void Delete<T>(T _entity) where T : class;
  9:         void Update<T>(T _entity) where T : class;
 10:         void Commit();
 11:         //Basic Select operations
 12:         IList<T> GetAll<T>() where T : class;
 13:         T GetById<T>(Func<T, bool> _condition) where T : class;
 14:     }
 15: }

Now we need the real Unit of Work that will inherit from our contract. We want also to inherit from IDisposable because otherwise we will not be able to keep alive our datacontext during the crud operations.

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Text;
  5: 
  6: namespace WPF.Tutorials.VMMV.DAL {
  7:     //Inherits IUnitOfWork and IDisposable
  8:     public class UnitOfWork:IUnitOfWork,IDisposable {
  9:         //A Static instance of the Linq Data Context
 10:         private static DataModelDataContext _service;
 11:         //The default constructor
 12:         public UnitOfWork() {
 13:             _service = new DataModelDataContext();
 14:         }

Now, the second step is to translate the UoW in something readable for Linq:

  1: //Add a new entity to the model
  2: public void Add<T>(T _entity) where T: class {
  3:     var table = _service.GetTable<T>();
  4:     table.InsertOnSubmit(_entity);
  5: }
  6: //Delete an existing entity from the model
  7: public void Delete<T>(T _entity) where T: class {
  8:     var table = _service.GetTable<T>();
  9:     table.DeleteOnSubmit(_entity);
 10: }
 11: //Update an existing entity
 12: public void Update<T>(T _entity) where T : class {
 13:     var table = _service.GetTable<T>();
 14:     table.Attach(_entity,true);
 15: }
 16: //Commit all the pending changes in the data context
 17: public void Commit() {
 18:     _service.SubmitChanges();
 19: }
 20: //Get the entire Entity table
 21: public IList<T> GetAll<T>()where T : class {
 22:     return _service.GetTable<T>().ToList();
 23: }
 24: //Get the first occurence that reflect the Linq Query
 25: public T GetById<T>(Func<T, bool> _condition) where T : class {
 26:     return _service.GetTable<T>().Where(_condition).FirstOrDefault();
 27: }
 28: 

Now we have a complete Unit of Work that we will use in each repository. Ops I forgot to mention that we will not have a real repository in our solution but a view model …

Tags:

WPF and MVVM tutorial 01, Introduction.

Add Comment | Jun 03, 2009

With Microsoft WPF technology, a new pattern is born and is going to be called MVVM (Model View ViewModel). This pattern is an hybrid from the old MVC and the old MVP patterns. Why a new pattern for the presentation?

  1. First of all WPF technology is giving us a kind of technology that can completely change the approach to design and code the UI. With the VMMV we can completely design an agnostic UI that doesn’t know the Model we are going to pass to it.
  2. Recycle, I will show you in this tutorial how to simply convert a WPF application into a Silverlight app.
  3. Better delegation and better design for a real n-tier application. In this example we will use LinqToSQL and WPF to build a complete n-tier application with the VMMV.
  4. Something that I do not like, TESTING THE UI!! Yes we can test the UI with WPF and VMMV combination.
  5. Abstractation. Now the view can be really abstract and you can use just a generic.xaml file and then give a style template to your model.

This is the schema (in my opinion) on how it should work an application with WPF and the VMMV implementation:

image

  • MODEL: anyone that has already worked on an n-tier application knows what it is. The model is the group of entities that will be exposed.
  • VIEW: the view is the graphical code XAML used to generate the UI, nothing more then that.
  • VIEWMODEL: the model for the view … or … the view for the model?! Anyway is a model of the view.

Before starting this tutorial I suggest you to download:

The next tutorial will show you how to create a simple DAL layer with LinQtoSQL and how we can implement the Unit of Work pattern to build a simple but solid data layer for our application.

You can also download the Visual Studio template here.

Tags:

NET RIA Service, #Part1 install.

Add Comment | May 31, 2009

In these series of posts I want to show how easy is to work with Visual Studio 2010, Silverlight 3 beta and the NET RIA Service.

Prerequisites and tutorials.

First of all we need to know what is NET RIA Service and how they can help us to write better business RIA applications.

NOTE: Unfortunately NET RIA will NOT work with the beta1 preview of Visual Studio 2010 so I recommend to use them into VS 2008 SP1.

Brad Adams and NET RIA Service overview has a very interesting post about the architecture of NET RIA Service.

Then, you must also watch the web cast at the MIX 2009. This will give a real touch of this technology that I am loving!

After all, you need now to work with the NET RIA service. I am going to write a series of posts about that, but you can also follow the tutorials over the web.

In order to develop with Silverlight 3 beta you need:

If you plan to work with Windows 7 and Visual Studio 2010, you can have a look also at my post on How to RDP into a Windows 7 virtual machine.

After that you will be able to follow my tutorials.

VMWare Workstation, bridge network and Windows 7.

Add Comment | May 31, 2009

VMWare workstation is a very good product for basic virtualizations, like having a personal netowork, implement a testing environment, test new products and/or operating systems.

You can download an evaluation version of VMWare Workstation 6.5, available also to support Windows 7 and x64 guest operating system.

Windows 7 and NET Framework 4.0

What I love about Microsoft products is the beta experience, that they offer always for free. At this link you can download an available virtual setup of Windows 7 with Visual Studio 2010 and NET Framework 4.

After that, in VMWare WRK you can simply import your Virtual PC machine and convert it into a VM disk.
If you prefer, you can download the ISO file of the Windows 7 and VS2010 64-bit in order to have a better experience into VMWare.

Bridge Networking

If you plan to add you Virtual Machine into your Host network, the only way is to use the Bridge Networking.

Bridged networking means a virtual machine runs on a virtual network that is "connected" to an existing physical network. This permits a virtual machine to appear as a full-fledged host on an existing physical network.

First of all you need to open VMWare, and from the menu Edit, open the Virtual Network Editor.

image

Here you can go to Host Virtual Network Mapping and choose the host adapter that will became our bridged adapter. Let’s say that we are using a wireless adapter with a subnet of 10.10.10.x, in this way our virtual machines will have the same subnet and will be available over the network.

After that, go into your Virtual Machine setup and change the network to Bridged.

image

Start the guest and change IP

Now we need to tell the guest system which IP it will need to have.
For Windows 7, open Network panel and choose Network and Sharing Center and then Change network adapter …

Open the TCP/IP and assign the IP you need, in order to make the machine visible to your network.

Share the Internet

Now, in order to give internet access also to our testing environment, let’s go back to the Host network adapter (in my case the Vista Wireless adapter).

Choose properties and sharing:

image

Now you can test this, by simply open the browser in the GUEST computer and type a web address.

Final step, RDP into the GUEST system

Now what we want to do is to work into the Guest, so we need to open an RDP connection and type the Guest IP address.

image

Do you want to use Aero from the HOST? Go into the properties of you remote connection and choose

image