Microsoft Dot Net Master

Microsoft Dot Net Master
Microsoft Dot Net Master

Friday, May 25, 2012

How to implement a reusable ICommand

Introduction

If you are using the MVVM (model-view-viewmodel) pattern, one of the most used mechanism to bind actions to the view are commands. To provide a command, you have to implement the ICommand interface. This is quite simple, but you have to do it over and over again. This is cumbersome.
The idea of this pattern build an universal command, that takes two delegates: One that is called, when ICommand.Execute(object param) is invoked, and one that evalues the state of the command when ICommand.CanExecute(object param) is called.
In addition to this, we need a method, that triggers the CanExecuteChanged event. This causes the ui element to reevaluate the CanExecute() of the commmand.

Sample implementation

 
public class DelegateCommand : ICommand
{
    private readonly Predicate<object> _canExecute;
    private readonly Action<object> _execute;
 
    public event EventHandler CanExecuteChanged;
 
    public DelegateCommand(Action<object> execute) 
                   : this(execute, null)
    {
    }
 
    public DelegateCommand(Action<object> execute, 
                   Predicate<object> canExecute)
    {
        _execute = execute;
        _canExecute = canExecute;
    }
 
    public override bool CanExecute(object parameter)
    {
        if (_canExecute == null)
        {
            return true;
        }
 
        return _canExecute(parameter);
    }
 
    public override void Execute(object parameter)
    {
        _execute(parameter);
    }
 
    public void RaiseCanExecuteChanged()
    {
        if( CanExecuteChanged != null )
        {
            CanExecuteChanged(this, EventArgs.Empty);
        }
    }
}

The Model-View-ViewModel Pattern

How the MVVM pattern became convenient

WPF has a very powerful databinding feature, that provides an easy one-way or two-way synchronization of properties. You can directly bind two WPF elements together, but the common use of databinding is to bind some kind of data to the view. This is done by using the DataContext property. Since the DataContext property is marked as inherited, it can be set on the root element of a view and it's value is inherited to all subjacent elements of the view.
One big limitation of using the DataContext property as data source is, that there is only one of it. But in a real life project you usually have more than one data object per view. So what can we do? The most obvious approach is to aggreate all data objects into one single object that exposes the aggregated data as properties and that can be bound to the DataContext. This object is called the view model.

Separation of logic and presentation

The MVVM pattern is so far only a convenient way to bind data to the view. But what about user actions, how are they handeld? The classic approach, known from WinForms is to register an event handler, that is implemented in the code-behind file of the view. Doing this has some disadvantages:
  • Having event handlers in the code-behind is bad for testing, since you cannot mock away the view.
  • Changing the design of the view often also requires changes in the code, since every element has it's different event handlers.
  • The logic is tightly bound to the view. It's not possible to reuse the logic in an other view
So the idea is to move the whole presentation logic to the view model by using another feature of WPF, namely Commands. Commands can be bound like data and are supported by many elements as buttons, togglebuttons, menuitems, checkboxes and inputbindings. The goal here is not to have any line of logic in the code-behind of a view. This brings you the following advantages
  • The view-model can easily be tested by using standard unit-tests (instead of UI-testing)
  • The view can be redesigned without changing the viewmodel, because the interface stays the same.
  • The view-model can even be reused, in sone special cases (this is usually not recommended)

What's the difference between MVVM, MVP and MVC?

There is always some confusion about the differences between model-view-presenter, model-view-controller an MVVM pattern. So I try to define and distinguish them a bit more clearly.

MVC - Model-View-Controller

The MVC pattern consists of one controller that directly gets all user input. Depending of the kind of input, he shows up a different view or modifies the data in the model. The model and the view are created by the controller. The view only knows about the model, but the model does not know about any other objects. The pattern was often used in good old MFC and now in ASP.NET MVC

MVP - Model-View-Presenter

In the MVP pattern, the view gets the user input and forwards it to the presenter. The presenter than modifies the view or the model depending on the type of user action. The view and the presenter are tightly coupled. There is a bidirectional one-to-one relation between them. The model does not know about the presenter. The view itself is passive, thats why it's called presenter pattern, since the presenter pushes the data into the view. This pattern is often seen in WinForms and early WPF applications.

MVVM - Model-View-ViewModel

The model-view-viewmodel is a typically WPF pattern. It consists of a view, that gets all the user input and forwards it to the viewmodel, typically by using commands. The view actively pulls the data from the viewmodel by using databinding. The model does not know about the view model.
Also check out this interesting article from Costas Bakopanos, a friend of mine, a discussion about the model, states and controllers in the MVVM environment.

Some MVVM Frameworks

Check out this handy tool to compare MVVM frameworks: MVVM Comparison Tool (Silverlight

A reference architecture for large WPF projects

Introduction

Choosing an adequate architecture is crucial for the success of a software project. You can have the best concepts, if your architecture does not perform, the user will have bad experiences while waiting for the application to load. Also aspects like it's robustness, maintainability or testability are important to address.
WPF provides a powerful databinding framework. If we could take advantage of this by using the MVVM pattern and decouple our views by dependency injection, we can build a powerful scaleable architecture.
These are the key components or patterns we want to use:
  • WPF DataBinding
  • Model-View-ViewModel pattern
  • Dependency Container (e.g. Unity)
  • Actions from the System.Windows.Interactivity library

How it works

The basic idea is to have a dependency container that builds up a view. The view has a viewmodel injected, that is bound to the DataContext. The viewmodel concentrates and provides data and commands for the view that it gets from services, that are injected by the constructor. The services live as singletons within the container.
Using this architecture allows you to build up loosely coupled views that interact magically together over common data coming from services in the background. It's very simple to rearrange or replace views, since they have to dependencies among each other.
Advantages of this architecture:
  • UI elements are easily replaced because of flexible databinding
  • The views are loosely coupled and quickly composed together
  • The viewmodel can be tested with conventional unit testing
  • Each service has a single purpose. They are easy to develop and make the architecture scalable.

Initializing the container and build up the main window

 
public class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        IUnityContainer container = new UnityContainer();
        container.RegisterType<ICustomerService, CustomerService>();
        container.RegisterType<IShoppingCartService, ShoppingCartService>();
 
        MainWindow mainWindow = container.Resolve<MainWindow>();
        mainWindow.Show();
    }
}
 
 

Injecting the viewmodel to the view

By adding a [Dependency] attribute to the property, the dependency container resolves and injects the specified type after creating the view. The injected viewmodel is directly set to the data context of the view. The view itself contains no other logic.
 
public class MainWindow : Window
{
    [Dependency]
    public MainWindowViewModel ViewModel
    {
        set { DataContext = value; }
    }
 
    public MainWindow()
    {
        InitializeComponent();
    }
}
 
 

Implementing the viewmodel

 
public class MainWindowViewModel
{
    private ICustomerService _customerService;
 
    public MainWindowViewModel(ICustomerService customerService)
    {
        _customerService = customerService;
        Customers = new ListCollectionView(customerService.Customers);
    }
 
    public ICollectionView Customers { get; private set; }
}
 
 

Binding the data to the view

 
<Window x:Class="WpfTutorial.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ListBox ItemsSource="{Binding Customers}" />
</Window>

How to implement undo/redo using MVVM

Introduction

One feature that many users demand is a neatless undo/redo integration. This means that the application allows the user to revert any modification he made - one by one - back to the start of the application and than eventually reapply them again. This improves the usability a lot, because it allows the user to carelessly use an unclear command, because he is certain, that he can undo it if he was wrong. Today undo/redo has gotten almost standard for any modern data editing application.

The MVVM-Pattern

Because of the strong databinding functionality in WPF, most applications are using the popular MVVM (Model-View-ViewModel) pattern. The idea of this pattern is basically to define a class that aggregates all data and commands for a certain view and provides them to the view as properties where it can bind to. Changes on properties are notified by an event on the INotifyPropertyChanged interface.

A concept of implementing undo/redo

A classical approach to implement undo/redo is to allow changes on the model only through commands. And every command should be invertible. The user than executes an action, the application creates a command, executes it and puts an inverted command on the undo-stack. When the user clicks on undo, the application executes the top-most (inverse) command on the undo-stack, inverts it again (to get the original command again) and puts it on the redo-stack. That's it.
Scenario 1: Executing an action
Scenario 2: Undoing an action

Adoption for WPF

We start with a base class that implements the INotifyPropertyChanged interface and provides a private method Notify(string propertyName).
 
public class NotifyableObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
 
    protected void Notify(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
 
 
Then we build the base class TrackableObject where all model objects or view models that are directly bound to the view should inherit from.
 
public class TrackableObject : NotifyableObject
{
    private readonly List<ITrackable> _trackableItems = new List<ITrackable>();
 
    public bool HasChanges
    {
        get { return _trackableItems.Any(i => i.HasChanges); }
    }
 
    public IModificationTracker ModificationTracker { get; set; }
 
    protected TrackableValue<T> RegisterTrackableValue<T>(string propertyName, 
           T defaultValue = default(T))
    {
        var property = new TrackableValue<T>(propertyName, Modify, Notify, defaultValue);
        _trackableItems.Add(property);
        return property;
    }
 
    protected TrackableCollection<T> RegisterTrackableCollection<T>()
    {
        var collection = new TrackableCollection<T>(Modify);
        _trackableItems.Add(collection);
        return collection;
    }
 
    private void Modify(Action doAction, Action undoAction, Action notification)
    {
        var modification = new Modification(doAction, undoAction, notification);
        modification.Execute();
        ModificationTracker.TrackModification(modification);
    }
}
 
 
To simplify the generation of modifactions when changing a property value, we build a generic wrapper for each property called TrackableValue.
 
public class TrackableValue<T> : ITrackable
{
    private readonly string _propertyName;
    private readonly Action<Action, Action, Action> _modifyCallback;
    private readonly Action<string> _notifyAction;
    private T _value;
 
    public TrackableValue(string propertyName, 
               Action<Action, Action, Action> modifyCallback,
               Action<string> notifyAction, T defaultValue)
    {
        _propertyName = propertyName;
        _modifyCallback = modifyCallback;
        _notifyAction = notifyAction;
        _value = defaultValue;
    }
 
    public bool HasChanges
    {
        get { return _originalValue.Equals(_value); }
    }
 
    public T Value
    {
        get { return _value; }
        set
        {
            var oldValue = _value;
            _modifyCallback(() => _value = value, 
                            () => _value = oldValue,
                            () => _notifyAction(_propertyName));
        }
    }
}
 
 
To same thing we need to do for collections to track add/remove of items from a collection
 
public class TrackableCollection<T> : IList<T>, ITrackable
{
    private readonly Action<Action, Action, Action> _modifyCallback;
    private readonly List<T> _list = new List<T>();
    private readonly List<T> _originalList = new List<T>();
 
    public TrackableCollection(Action<Action, Action, Action> modifyCallback)
    {
        _modifyCallback = modifyCallback;
    }
 
    public event EventHandler<EventArgs<T>> ItemAdded;
    public event EventHandler<EventArgs<T>> ItemRemoved;
    public event EventHandler CollectionChanged;
 
    public bool HasChanges
    {
        get
        {
            if( _list.Count == _originalList.Count)
            {
                return _list.Where((item, index) => 
                       !item.Equals(_originalList[index])).Any();
            }
            return true;
        }
    }
 
    public void AcceptChanges()
    {
        _originalList.Clear();
        _originalList.AddRange(_list);
    }
 
    public IEnumerator<T> GetEnumerator()
    { 
        return _list.GetEnumerator();    
    }
 
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
 
    public void Add(T item)
    {
        _modifyCallback(() =>
        {
            _list.Add(item); 
            ItemAdded.Notify(this, new EventArgs<T>(item));
        }, 
        () =>
        {
            _list.Remove(item);
            ItemRemoved.Notify(this, new EventArgs<T>(item));
        }, 
        OnCollectionModified);
    }
 
    public void Clear()
    {
        var items = new T[_list.Count];
        _list.CopyTo(items);
        _modifyCallback(() =>
        {
            _list.ForEach(i => ItemRemoved.Notify(this, new EventArgs<T>(i)));
            _list.Clear();
        }, 
        () =>
        {
            _list.AddRange(items);
            _list.ForEach(i => ItemAdded.Notify(this, new EventArgs<T>(i)));
        }, 
        OnCollectionModified);
    }
 
    public bool Contains(T item)
    {
        return _list.Contains(item);
    }
 
    public void CopyTo(T[] array, int arrayIndex)
    {
        _list.CopyTo(array, arrayIndex);
    }
 
    public bool Remove(T item)
    {
        var result = _list.Contains(item);
        _modifyCallback(() =>
        {
            _list.Remove(item);
            ItemRemoved.Notify(this, new EventArgs<T>(item));
        }, 
        () =>
        {
            _list.Add(item);
            ItemAdded.Notify(this, new EventArgs<T>(item));
        }, 
        OnCollectionModified);
        return result;
    }
 
    public int Count
    {
        get { return _list.Count; }
    }
 
    public bool IsReadOnly
    {
        get { return false; }
    }
 
    public int IndexOf(T item)
    {
        return _list.IndexOf(item);
    }
 
    public void Insert(int index, T item)
    {
        _modifyCallback(() =>
        {
            _list.Insert(index, item);
            ItemAdded.Notify(this, new EventArgs<T>(item));
        }, 
        () =>
        {
            _list.Remove(item);
            ItemRemoved.Notify(this, new EventArgs<T>(item));
        }, 
        OnCollectionModified);
    }
 
    public void RemoveAt(int index)
    {
        var item = _list[index];
        _modifyCallback(() =>
        {
            _list.Remove(item);
            ItemRemoved.Notify(this, new EventArgs<T>(item));
        }, 
        () =>
        {
            _list.Insert(index, item);
            ItemAdded.Notify(this, new EventArgs<T>(item));
        }, 
        OnCollectionModified);
    }
 
    public T this[int index]
    {
        get { return _list[index]; }
        set
        {
            var oldItem = _list[index];
            _modifyCallback(() =>
           {
               _list[index] = value;
               ItemAdded.Notify(this, new EventArgs<T>(value));
           }, 
           () =>
           {
               _list[index] = oldItem;
               ItemRemoved.Notify(this, new EventArgs<T>(oldItem));
           }, 
           OnCollectionModified);
        }
    }
 
    private void OnCollectionModified()
    {
        CollectionChanged.Notify(this, EventArgs.Empty);   
    }
}

Wednesday, May 2, 2012

WCF Question and Answer

What is WCF?
Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for services, enabling you to expose CLR types as services, and to consume other services as CLR types. WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on systems that support it.
Difference between WCF and Web services?
1.Web Services can be accessed only over HTTP
2.Web Services works in stateless environment
WCF is flexible because its services can be hosted in different types of applications. The following lists several common scenarios for hosting WCF services: 1. IIS
2. WAS
3. Self-hosting
4. Managed Windows Service
What are the various ways of hosting a WCF service?
Self hosting the service in his own application domain. This we have already covered in the first section. The service comes in to existence when you create the object of ServiceHost class and the service closes when you call the Close of the ServiceHost class. Host in application domain or process provided by IIS Server. Host in Application domain and process provided by WAS (Windows Activation Service) Server.
What are three major points in WCF?
We Should remember ABC.
Address - Specifies the location of the service which will be like http://Myserver/MyService.Clients will use this location to communicate with our service.
Binding - Specifies how the two paries will communicate in term of transport and encoding and protocols.
Contract - Specifies the interface between client and the server.It's a simple interface with some attribute.
What was the code name for WCF?
The code name of WCF was Indigo . WCF is a unification of .NET framework communication technologies which unites the following technologies:- NET remoting MSMQ Web services COM+
What are the main components of WCF?
The main components of WCF are 1. Service class 2. Hosting environment 3. End point
What are different elements of WCF Srevices Client configuration file?
WCF Services client configuration file contains endpoint, address, binding and contract. A sample client config file looks like
What is Proxy and how to generate proxy for WCF Services?
WCF Services client configuration file contains endpoint, address, binding and contract. A sample client config file looks like
The proxy is a CLR class that exposes a single CLR interface representing the service contract. The proxy provides the same operations as service's contract, but also has additional methods for managing the proxy life cycle and the connection to the service. The proxy completely encapsulates every aspect of the service: its location, its implementation technology and runtime platform, and the communication transport.
The proxy can be generated using Visual Studio by right clicking Reference and clicking on Add Service Reference. This brings up the Add Service Reference dialog box, where you need to supply the base address of the service (or a base address and a MEX URI) and the namespace to contain the proxy.
Proxy can also be generated by using SvcUtil.exe command-line utility. We need to provide SvcUtil with the HTTP-GET address or the metadata exchange endpoint address and, optionally, with a proxy filename. The default proxy filename is output.cs but you can also use the /out switch to indicate a different name.
SvcUtil http://localhost/MyService/MyService.svc /out:Proxy.cs
When we are hosting in IIS and selecting a port other than port 80 (such as port 88), we must provide that port number as part of the base address:
SvcUtil http://localhost:88/MyService/MyService.svc /out:Proxy.cs
What are contracts in WCF?
In WCF, all services expose contracts. The contract is a platform-neutral and standard way of describing what the service does.
WCF defines four types of contracts.
Service contracts
Describe which operations the client can perform on the service. There are two types of Service Contracts. ServiceContract - This attribute is used to define the Interface. OperationContract - This attribute is used to define the method inside Interface. [ServiceContract]
interface IMyContract
{
[OperationContract]
string MyMethod( );
}
class MyService : IMyContract
{
public string MyMethod( )
{
return "Hello World";
}
}
Data contracts
Define which data types are passed to and from the service. WCF defines implicit contracts for built-in types such as int and string, but we can easily define explicit opt-in data contracts for custom types.
There are two types of Data Contracts.
DataContract - attribute used to define the class
DataMember - attribute used to define the properties.
[DataContract]
class Contact
{
[DataMember]
public string FirstName;
[DataMember]
public string LastName;
}
If DataMember attributes are not specified for a properties in the class, that property can't be passed to-from web service.
Fault contracts
Define which errors are raised by the service, and how the service handles and propagates errors to its clients.
Message contracts
Allow the service to interact directly with messages. Message contracts can be typed or untyped, and are useful in interoperability cases and when there is an existing message format we have to comply with.
What is the address formats of the WCF transport schemas?
Address format of WCF transport schema always follow [transport]://[machine or domain][:optional port] format. for example: HTTP Address Format http://localhost:8888 the way to read the above url is "Using HTTP, go to the machine called localhost, where on port 8888 someone is waiting" When the port number is not specified, the default port is 80. TCP Address Format net.tcp://localhost:8888/MyService When a port number is not specified, the default port is 808: net.tcp://localhost/MyService NOTE: Two HTTP and TCP addresses from the same host can share a port, even on the same machine. IPC Address Format net.pipe://localhost/MyPipe We can only open a named pipe once per machine, and therefore it is not possible for two named pipe addresses to share a pipe name on the same machine. MSMQ Address Format net.msmq://localhost/private/MyService net.msmq://localhost/MyService
What is endpoint in WCF?
Every service must have Address that defines where the service resides, Contract that defines what the service does and a Binding that defines how to communicate with the service. In WCF the relationship between Address, Contract and Binding is called Endpoint. The Endpoint is the fusion of Address, Contract and Binding.
What is binding and how many types of bindings are there in WCF?
A binding defines how an endpoint communicates to the world. A binding defines the transport (such as HTTP or TCP) and the encoding being used (such as text or binary). A binding can contain binding elements that specify details like the security mechanisms used to secure messages, or the message pattern used by an endpoint.
WCF supports nine types of bindings.
Basic binding
Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy ASMX web service, so that old clients can work with new services. When used by the client, this binding enables new WCF clients to work with old ASMX services.
TCP binding
Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the intranet. It supports a variety of features, including reliability, transactions, and security, and is optimized for WCF-to-WCF communication. As a result, it requires both the client and the service to use WCF.
Peer network binding
Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer network-enabled client and services all subscribe to the same grid and broadcast messages to it.
IPC binding
Offered by the NetNamedPipeBinding class, this uses named pipes as a transport for same-machine communication. It is the most secure binding since it cannot accept calls from outside the machine and it supports a variety of features similar to the TCP binding.
Web Service (WS) binding
Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet.
Federated WS binding
Offered by the WSFederationHttpBinding class, this is a specialization of the WS binding, offering support for federated security.
Duplex WS binding
Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also supports bidirectional communication from the service to the client.
MSMQ binding
Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer support for disconnected queued calls.
MSMQ integration binding
Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from MSMQ messages, and is designed to interoperate with legacy MSMQ clients.
Where we can host WCF services?
Every WCF services must be hosted somewhere. There are three ways of hosting WCF services.
They are
1. IISM
2. Self Hosting
3. WAS (Windows Activation Service)
What is address in WCF and how many types of transport schemas are there in WCF?
Address is a way of letting client know that where a service is located. In WCF, every service is associated with a unique address. This contains the location of the service and transport schemas.
WCF supports following transport schemas
HTTP
TCP
Peer network
IPC (Inter-Process Communication over named pipes)
MSMQ
The sample address for above transport schema may look like
http://localhost:81
http://localhost:81/MyService
net.tcp://localhost:82/MyService
net.pipe://localhost/MyPipeService
net.msmq://localhost/private/MyMsMqService
net.msmq://localhost/MyMsMqService
What is service and client in perspective of data communication?
A service is a unit of functionality exposed to the world.
The client of a service is merely the party consuming the service