Notes from PDC10

Here are some of my notes/findings from what is going on at PDC 10, Redmond:


 


  1. Microsoft is betting big time on Windows Phone 7, Azure and Internet Explorer 9 (more focus on HTML 5)
  2. Microsoft code-name “Dallas” now officially called as DataMarket (an apt name!)
  3. Microsoft is working with its partners (Accenture & SAS) to give analytical capabilities as a service using SQL Azure
  4. Reporting Services (SQL Server Reporting Services) is now available on Azure using SQL Azure
  5. A new role added (previously we had Web and Worker roles): VM Role
    1. Allows you to upload a SQL Server 2008 R2 64-bit VHD file and use it for your applications
    2. VHD can be configured however you want and upload it
  6. New guest OS: Windows Server 2008 R2 (previously it was only WS 2008) – all 64-bit. No 32-bit business on Windows Azure
  7. New VM size: X-Small
    1. Single 1.0GHz Processor, 5Mbps network bandwidth and 768MB Memory
    2. Targeted for small applications with low processing and I/O
    3. Also meant for Azure development, prototyping, etc.
    4. Network throttled
    5. Cost – 2 cents/compute hour
  8. More admin features/access (including Remote Desktop) to your VM instances
  9. Team Foundation Server 2010 on the Cloud now!
  10. Full IIS support on Windows Azure!
  11. The next version of C# and Visual Basic .NET will have language level support for asynchronous programming (expect new keywords)
  12. Azure Connect for connecting Azure apps with on-premise applications
    1. Share data between Azure and on-premise apps

 


Good for now!

O…Data

Applications use data from many sources – from mainframe to flat files, XML, RDBMS, Excel, Microsoft Access and the list goes on. In parallel, we have many data access APIs/libraries based on the development platform: for C/C++ applications, we have ODBC, for COM/DCOM there is ADO, Java world enjoys JDBC and .NET applications have ADO.NET. That said, in this Internet ubiquitous world, data is increasing exposed via Internet too (a recent entry into this arena is Microsoft “Dallas”). More matured standards/protocols around the Internet, ever evolving network technology stacks and universal data representation schemes are making organizations inclining slowly towards this new model of “data over internet”, both on the consuming as well as publishing ends.



So how do we access data that is exposed over the web in a standard method irrespective of the platform? Enter OData! OData (Open Data) is the ODBC/ADO/JDBC/ADO.NET equivalent for accessing “internet enabled” business data. Independent of operating systems and development platforms, OData is a data access API (application-level protocol, to be specific – remember the OSI layers from good old college days?) based on other standards: HTML, REST and AtomPub (RFC5023) (a data publishing protocol which itself is based on the Atom syndication protocol). OData makes certain extensions to AtomPub to deliver a richer set of functionality. In the diagram below, the left-hand side represents the payload or data exchange format stack and the righ-hand side represents communication stack for OData.



Since all the constituent standards of OData are operating system and programming language independent, you can use OData to consume data (from any OData publisher) from a variety of development environments, OS platforms and devices.




From a consumer’s perspective, OData lets you do resource-specific CRUD operations purely via HTTP/HTTPS using plain XML, Atom or JSON as the payload. On the backend, the OData publisher uses REST model to expose its resources (Consumers, Products, Orders, etc.) and CRUD and service-specific operations on those resources. Of course, the publisher need not support all the CRUD operations on all the resources; it can decide and set appropriate operation permissions on the resources and actions on its own. Let us see an example: assume we have a simple database with a list of law firms each with multiple lawyers associated with it. Each lawyer can have more than one area of practice (such as Divorce, Corporate Compliance and Mortgage). Suppose you want to list the available lawyers and had it been an RDBMS you would write an SQL query like the following:


SELECT * FROM Lawyers;


In OData, you would make a simple HTTP GET request to the OData service as:


http://odata.example.org/Lawyers


Here, http://odata.example.org/ is called the service root URI and Lawyers is the resource path. A service can publish any number of resources at the same root URI. You can pass additional parameters and commands via URI query strings to fintune and shape the data. The service returns the result, list of lawyer entities in this case, in XML format conforming to AtomPub standards. A typical output is shown below highlighting a single entry from the feed (for brievety, many entities and shown collapaed). Note that the output XML does not show the complete the entity information, rather a link to edit that entity is included (append the href attribute value to the xml:base value at the top as in http://localhost:5684/Lawyer.svc/Lawyers(93). A OData client can use this URI to get the editable fields from the publisher). Also note that the content element has the primary key name and its value for the entry.



Extending the above query a bit further, if you want the list of lawyers specializing in accident related law, the typical SQL query would be:


SELECT * FROM Lawyers WHERE PracticeArea=‘Accident’;


The OData HTTP request doing the same job would be:


http://odata.example.org/Lawyers$filter=PracticeArea eq ‘Accident’;


This screenshot below shows a sample feed output for this query (there are two entries satisfying this filter but second one is collapsed):



We can also have more than one filter condition:


SELECT * FROM Lawyers WHERE PracticeArea=‘Accident’ AND City=‘Chicago’;

http://odata.example.org/Lawyers$filter=PracticeArea eq ‘Accident’ and City eq ‘Chicago’


To request specific columns (projection) as in the following:


SELECT LawyerID, Name, Exp FROM Lawyers WHERE Exp > 10;

http://odata.example.org/lawyers$filter=exp gt 10&$select=LawyerID,Name,Exp


The below XML fragment from the actual output highlights the projected properties from the above REST query:



To get a specific entity by its key value:


SELECT * FROM Lawyers WHERE LawyerID=1940

http://odata.example.org/lawyers(1940)/



How about composite primary keys? Pretty simple:


SELECT * FROM Lawyers WHERE LawyerID=1940 AND OfficeID=’IL2159′;

http://odata.example.org/lawyers(lawyerid=1940, officeid=’IL2159′)/


Notice that non-numeric values are enclosed in quotes in the URI query string irrespective of their context. To access a specific property, say birth date, of the entity with ID 491:


SELECT BirthDate FROM Lawyers WHERE LawyerID=491

http://odata.example.org/lawyers(491)/birthdate



If you want just the value without the XML part, append $value to the URI as in:



Here are some interesting URI queries for your curiosity!! J


http://odata.example.org/offices(‘IL2159′)/lawyers/$top=5&$orderby=name desc

http://odata.example.org/offices(‘NYC19′)/lawyers/$filter=(practicearea eq ‘Loans’) and (startswith(name, ‘Nick’) eq true)&$orderby=name desc

http://odata.example.org/offices(‘WAM2′)/lawyers/$filter=(address/city eq ‘Redmond’) and (practicearea eq ‘corporate’ or practicearea eq ‘banking’) and (year(jdate) ge 1999)&$skip=10&$top=10&$select=Name,jdate


These URIs may look ascaringly complex but if you pay close attention to them with a pinch of SQL semantics, they are straight forward and easy to understand! For more filtering options, refer to section 4 of the OData URI Conventions.


By default, the OData service returns results in AtomPub XML format. However, if you would prefer you can get it in JSON too (if the publisher supports it).


http://odata.example.org/Lawyers$filter=City eq ‘Chicago’&$select=LawyerID,Name,City&$format=json


WCF Data Services (formerly ADO.NET Data Services, codename “Astoria”) currently does not support this query string convention for returning JSON data. Instead you have to specify the MIME type for JSON in the Accept header of the HTTP request.


GET http://localhost:5684/Lawyer.svc/Lawyers(7350)/ HTTP/1.1

Accept: application/json

Host: localhost:5684

HTTP/1.1 200 OK

Server: ASP.NET Development Server/10.0.0.0

Date: Wed, 13 Oct 2010 20:21:12 GMT

X-AspNet-Version: 4.0.30319

DataServiceVersion: 1.0;

Content-Length: 458

Cache-Control: no-cache

Content-Type: application/json;charset=utf-8

Connection: Close

 

{

“d” : {

“__metadata”: {

“uri”: “http://localhost:5684/Lawyer.svc/Lawyers(7350)”, “type”: “LawyerOData.LawyerInfo”

}, “LawyerID”: 7350, “Name”: “John Woodlee”, “Exp”: 17, “PracticeArea”: “Employment”, “BirthDate”: “\/Date(20995200000)\/”, “JDate”: “\/Date(423014400000)\/”, “OfficeID”: “MAB1″, “Address”: {

“__metadata”: {

“type”: “LawyerOData.AddressInfo”

}, “AddressInfoID”: 72, “AddressLine”: “Cinema Way”, “City”: “Natick”, “State”: “MA”

}

}

}


Now that we have seen some basic examples of OData requests, let us briefly discuss some of the concepts that make OData as a whole.


Property: is the most granular item in a OData data stream, equivalent to a column in a database table. A property is typed and can be a simple type (integer, float, string, boolean, etc) or a complex type – another entry (see next para). Think of this is a class property which is also a class as in Lawyer. Eample: http://odata.example.org/lawyers(491)/Name refers to the Name property of the lawyer ID 491.


Entry: is a structured item that contains one or more properties, much like a row in a table. An entry can have any number of properties, with a single or composite primary key. Example: http://odata.example.org/lawyers(491)/ represents a lawyer entry whose primary key is 491.


Feed: is a collection of entries and as you might have probably guessed it is conceptually like a database table. Typically OData services expose multiple feeds representing mutliple resource sets. For example, the URI http://odata.example.org/lawyers represents the lawyer feed.


Service Documents: are XML docuents OData services expose for the clients to discover the feeds available. Generally, a OData service makes its service document available at its root URI. A sample service document exposing a single feed Lawywers is shown below:



Metadata: desribes the strucure of the entries available in the service feed. It provides details including the entry name, its constituent property names and their types, primary key and entry relationships in XML form. Think of this as what WSDL is to web services. (If you know Enity Framework, then the metadata is nothing but the CSDL document of the entity data model (EDM)). You can access a service’s metadata by appending $metadata to the service root URI as in http://odata.example.org/$metadata. OData clients such as Visual Studio’s Add Service Reference feature uses this URI to generate the client-side proxy and entity classes. The below screenshot shows the EDM model for the sample OData service I used for this article:



Associations: As mentioned above, an association describes the relationship between two entries (in database terms, foreign key relationships). Association information is available as part of the service metadata. CSDL referes association properties of entries as navigation properties because they are used to navigate from a parent entry to child ones to grand-children and so on. Example: http://odata.example.org/lawyers(491)/addresses represents the list of addresses (feed) that the lawyer ID 491 has.


In OData, associations are called Links. Don’t worry about these terminologies because they are just different names to the same thing depending on the context.


Though OData is new, it is already supported by products. Some of them are Microsoft SharePoint 2010, Windows Azure’s Table Stoage Services and IBM Websphere. Of course you can add OData support for your own data/products by writing your own data service provider (DSP).


If you would like to know more about OData protocol, check out http://www.odata.org. It has everything you need to get started and use the protocol in production environments. It also has some public sample OData URIs that you can play with and understand it better.


I hope this post gave you a broad idea about OData and its querying features. I’ll talk about update, delete and insert features in a future post.

Comparing WCF Message Encoding Options

As you know WCF supports three types of message encodings (Encoding is the process of converting serialized object graph data into a format that can be transmitted over a network or saved to a file for later retrieval. Encoded data can be fed into a deserializer to hydrate the original object). Each encoding mechanism caters to different purpose but mostly decides the interoperability aspect of the service. They also produce different encoded output for the same logical data. In this post, I want to highlight the differences between these encoding types in terms of the actual payload they create for a given serialized object. In other words, we will see to what extent each of them bloats the original serialized object and which one is the least bloating.


WCF also supports three types of serializers:
XmlSerializer,
NetDataContractSerializer and
DataContractSerializer. Without getting into deep:
XmlSerializer provides the most customization options on the serialized XML and extensive support for XSD.
NetDataContractSerializer and
DataContractSerializer provide limited control over the generated (serialized) XML and limited support for XSD. For example, both the
DataContractSerializer versions serialize an object into element-only XML; you cannot for instance force a property to appear as an attribute. They also support versioning.
NetDataContractSerializer however scores better over
DataContractSerializer by providing high type fidelity by sharing assembly and type information in the serialization. This implies that both the service and client should have access to the same assembly containing the types exchanged in the WCF calls. Since most scenarios use (and also as the default)
DataContractSerializer, the rest of this article uses this serializer only.


 All right, back to encoding options. As said earlier, WCF has three types of encoding options: Text (plain XML), MTOM (Message Transmission Optimization Mechanism) and Binary. I am having a couple of simple data contracts with default settings/configurations applied to them:



using System.Collections.Generic;
using System.ServiceModel;




 //




[DataContract]
public class PersonInfo
{
    [DataMember]
    public string Name;
    [DataMember]
    public short Age;
    [DataMember]
    public char Gender;
    [DataMember]
    public List<Department> PreviousDepartments;
    [DataMember]
    public byte[] Photo = new byte[1000];
    public PersonInfo()
    {
        PreviousDepartments = new List<Department>();
        new Random().NextBytes(this.Photo);
    }
}

[DataContract]
public class Department
{
    [DataMember]
    public int DepartmentID;
    [DataMember]
    public string DepartmentName;
}


This small piece of code initializes an instance of
PersonInfo with three child complex types:


var pi = new PersonInfo() {Name="Susan Davis", Age=39, Gender='F'};
pi.PreviousDepartments.Add (new Department(){DepartmentID=1, DepartmentName="Sales"});
pi.PreviousDepartments.Add (new Department(){DepartmentID=3, DepartmentName="Administration"});
pi.PreviousDepartments.Add (new Department(){DepartmentID=3, DepartmentName="Engineering"});




Nothing special! Let us see how the text (XML) serializer encodes this object with the following code:



MemoryStream ms = new MemoryStream ();
XmlDictionaryWriter tw = XmlDictionaryWriter.CreateTextWriter (ms);
DataContractSerializer dcs = new DataContractSerializer (typeof (PersonInfo));
dcs.WriteObject (tw, pi);
tw.Flush ();
DumpStream (ms);




DumpStream() is a simple helper method to dump the encoded object into the console window:


private static void DumpStream (MemoryStream s)
{
    Console.BackgroundColor = ConsoleColor.Yellow;
    Console.ForegroundColor = ConsoleColor.Red;
    Console.WriteLine ("Content length: {0} bytes", s.Length);
    Console.ResetColor ();
    s.WriteTo (Console.OpenStandardOutput ());
    Console.WriteLine ();
}




And the output looks like this:


WCF Text Encoding


Note that the default behavior of plain text encoding is to base64-encode any binary data. Let us see the output of MTOM encoding for the same object instance:



tw = XmlDictionaryWriter.CreateMtomWriter (ms = new MemoryStream (), Encoding.UTF8, Int32.MaxValue, "");
dcs.WriteObject (tw, pi);
tw.Flush ();
DumpStream (ms);




 WCF MTOM Encoding


Note that the MTOM is basically a multi-part MIME message where binary data is base64-encoded and streamed into a separate section of the message. The original XML just makes a reference to this section.


WCF MTOM Encoding


However, MTOM encoding creates multi-part messages only if the base64-encoded data size exceeds 1024 bytes. Otherwise, it simply keeps the base64 content inline and as a result brings down the overall message size (280 bytes less in this case) as there is no MIME header and additional section reference.


WCF MTOM Encoding


Let us see the binary encoding now:



tw = XmlDictionaryWriter.CreateBinaryWriter (ms = new MemoryStream ());
dcs.WriteObject (tw, pi);
tw.Flush ();
DumpStream (ms);




 Produce the following output:


WCF Binary Encoding


As you can see, binary encoding produces the smallest wire size compared to the other two encodings. Note that it also lacks the standard XML headers and it is a bit difficult to make out the actual content too unlike the other two. I heard a couple of beeps as well when this message was shown J Actually, MTOM by nature is supposed to perform better compared to text but this wasn’t the case in the above test scenario (1024 bytes of binary data). So, I went further and did few more iterations using the same code but increasing the binary array size in each iteration to see how each of these encoding do with increase binary data. As expected, after a point, MTOM performed better than text and came near (but no close) to binary encoding.



WCF Encoder Comparison


This graph is just an illustration to show and compare the performance of the three encoding options in WCF. Microsoft may change their implementation in future to bring the differences smaller. To summarize:


  1. Text encoding gives support for plain XML and provides the widest interoperability compared to others.
  2. Binary is efficient and produces smallest message size among the others. This should be considered when both the service and consumer are WCF-based.
  3. MTOM is good for objects containing binary data but it still outputs plain XML for normal object properties. This also provides significant interoperability because W3C has standardized MTOM.

Why I Love Belkin

I am a big fan of Belkin brand! I am not sure if you too fall in this category or not, but I am always amazed by their “cool” products. Long long ago, I was looking for a gadget or some sort of transceiver than can transfer and receive all formats of audio and video signals (composite, S-Video and component) from the source to the receiver (a TV) kept in another room. Obviously I didn’t want to run lengthy wires between the source and the receiver. After some Internet search I came across Belkin’s PureAV RemoteTV, – exactly what I was looking for. The love with Belkin brand started then but it was not possible to ship the product outside the US despite my desperation and only ended with disappointment. Since then I have been using many products of them (their N+ ADSL modem + router, iPhone sleeve J, 8-port Ethernet switch, N+ WiFi USB adapter, powered 7-port USB hub and power surge protector all found a place at my home). Though Belkin entered Indian market about two years ago, only limited products of them are available. All right, why am I telling all these now? Well, I had been looking for a Bluetooth audio receiver and of course came across few products from Sony and others. The intention was to play music from my laptop, Mac or mobile phone on my home theater via a Bluetooth receiver connected to the AV receiver.



Though Sony’s Indian website mentioned about a Bluetooth transmitter/receiver, it is still not available in any retail shop. Yesterday when I was buying some MacBook accessories, I accidently found a Belkin Bluetooth receiver!! J Bought it immediately and hooked it up with my AV receiver. My yet another search ended and wish fulfilled by Belkin! J


[Product image courtesy: Belkin.com]


[I am no way related to the Belkin, the company. I don't work for them nor do I resell their products. I am just one happy consumer of their products!]

Model-View-ViewModel Pattern 101 (Part 4)

Read part 1 here, part 2 here or part 3 here.

This is a sort of summary post of my MVVM Pattern 101 series, talking about the frameworks available for MVVM development. There are many open-source frameworks available for MVVM-based development. Most of the frameworks support WPF as well as Silverlight including the new Windows Phone 7 platform. Of these frameworks, notable ones are Prism from Microsoft’s P&P team, Caliburn and MVVM Light. Prism is a composite UI framework for WPF and Silverlight. It also uses Inversion of Control (IoC)/Dependency Injection pattern. This allows you to use other IoC frameworks such as Spring.NET, Microsoft’s Unity or your own with MVVM development. Caliburn and MVVM Light are 3rd party MVVM-dedicated frameworks. If you would like to see a list of some of the MVVM frameworks available today, check here. The author has made the comparison itself as a Silverlight app!

    Talking about frameworks doesn’t mean you can’t develop your own. Watch a nice presentation on building own MVVM framework here.

Model-View-ViewModel Pattern 101 (Part 3)

This is 3rd of my multi-part series on MVVM 101. Read part 1 here and part 2 here.

From an implementation perspective, ViewModel is a just class satisfying certain requirements and you follow a few simple steps to have a working one. Remember the key part in MVVM is the VM, the real controller, because View is just your WPF UI and Model is either an entity object or data transfer object. Let us say we want to display some very basic details about an insurer; the listing dialog will display details such as first name, last name, state and his dependent list. Let us also assume we already have domain objects for the insurer and dependent entities (I deliberately made Dependents as a complex type to show how collection properties can be dealt with in MVVM). Here is our simple model:

public class InsuranceInfo
{
    public string FirstName {getset;}
    public string LastName {getset;}
    public List<FDependents> Dependents {getset;}
    public string State {getset;}
}

public class FDependents
{
    public string Relationship {getset;}
    public string DepName {getset;}
    public short Age {getset;}
}


 

A simple UI we are going to build our VM against to show the above model:


Let’s go ahead and get the missing piece – ViewModel. As a convention, all the VM classes have the “ViewModel” suffix and I am calling ours as InsuranceViewModel.

Step 1: Add special properties to the VM for the UI to bind to

    Any data displayed in the UI should have a corresponding property in the VM class. These properties are special in that any change to their values should be detectable by the binding engine and update the bound controls accordingly. Hence the VM should implement

INotifyPropertyChanged
interface and with collection properties wrapped by
ObservableCollection<>
.

public class InsuranceViewModel : INotifyPropertyChanged
{
    private string _fn;
    private string _ln;
    private string _state;

    public event PropertyChangedEventHandler PropertyChanged;
    public ObservableCollection<FDependents> Dependents {getprivate set;}
    public string FirstName {
        get {return _fn;}
        set {
            if (_fn != value) {
                _fn = value;
                RaisePropertyChanged (“FirstName”);
            }
        }
    }
    public string LastName {
        get {return _ln;}
        set {
            if (_ln != value) {
                _ln = value;
                RaisePropertyChanged (“LastName”);
            }
        }
    }
    public string State {
        get {return _state;}
        set {
            if (_state != value) {
                _state = value;
                RaisePropertyChanged (“State”);
            }
        }
    }
    public EditCommand EditCmd {private set;get;}
    private void RaisePropertyChanged (string p) {
        if (PropertyChanged != null) {
            PropertyChanged (thisnew PropertyChangedEventArgs (p));
        }
    }
}


 

Note that I have implemented the properties as property methods instead of fields because we should raise property change notification whenever the property values are changed.

Step 2: Provide ICommand properties for applicable control events

Since our UI has save option, a command property,

EditCmd
of type
EditCommand
is also included in the above code. The command class looks like this:

public class EditCommand : ICommand {
    private InsuranceViewModel _vm = null;
    public event EventHandler CanExecuteChanged {
        add {CommandManager.RequerySuggested += value;}
        remove {CommandManager.RequerySuggested -= value;}
    }
    public bool CanExecute (object parameter) {
        if (parameter != null) {
            var cp = parameter as InsuranceViewModel;
            return !(cp.FirstName == “” || cp.LastName == “” || cp.State == “”);
        }
        else
            return true;
    }

    public void Execute (object parameter) {
        if (parameter != null) {
            var cp = parameter as InsuranceViewModel;
            MessageBox.Show (String.Format(“{0}, {1}, {2}”
                cp.FirstName, cp.LastName, cp.State));
        }
    }

    public EditCommand (InsuranceViewModel vm) {_vm = vm;}
}

It is very important that the command classes derive from

ICommand
. The
CanExecute
method tells if the action is available at any moment so that the control can disable itself or take appropriate action. This method will be called at appropriate times by the commanding infrastructure. The above code states that if at least one of first name, last name or state is empty, the Edit command should not be available.
Execute
method is called as a result of the control event (the event handler!). It is a common design that commands are initialized with a view model instance to delegate data service operations back to the view model itself.

Step 3: Hook up a ViewModel instance with UI markup

<Window x:Class=”MVVMDemo.MainWindow”
        xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
        xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
        Title=”MVVM Demo” Height=”352″ Width=”525″ Loaded=”Window_Loaded”>
    <Grid Height=”Auto”>
        <ListView Margin=”12,100,0,58″ Name=”lvwInsuranceInfo” 
                  SelectionMode=”Single” ItemsSource=”{Binding Path=Dependents}” 
                  HorizontalAlignment=”Left” Width=”352″>
            <ListView.View>
                <GridView AllowsColumnReorder=”False”>
                    <GridViewColumn Header=”Relationship” 
                                    DisplayMemberBinding=”{Binding Path=Relationship}” />
                    <GridViewColumn Header=”Name” 
                                    DisplayMemberBinding=”{Binding Path=DepName}” />
                    <GridViewColumn Header=”Age” 
                                    DisplayMemberBinding=”{Binding Path=Age}” />
                </GridView>
            </ListView.View>
        </ListView>
        <Button Content=”_Close” Margin=”0,0,12,12″ Name=”btnClose” 
                Click=”btnClose_Click” HorizontalAlignment=”Right” Width=”105″ 
                Height=”24″ VerticalAlignment=”Bottom” />
        <Label Content=”First Name:” Height=”24″ HorizontalAlignment=”Left” 
               Margin=”10,10,0,0″ Name=”lblFN” Padding=”0″ VerticalAlignment=”Top” 
               VerticalContentAlignment=”Center” />
        <Label Content=”Last Name:” Height=”24″ HorizontalAlignment=”Left” 
               Margin=”10,40,0,0″ Name=”label2″ Padding=”0″ VerticalAlignment=”Top” 
               VerticalContentAlignment=”Center” />
        <Label Content=”State:” Height=”24″ HorizontalAlignment=”Left” Margin=”10,70,0,0″ 
               Name=”label3″ Padding=”0″ VerticalAlignment=”Top” 
   
            VerticalContentAlignment=”Center” />
        <Button Command=”{Binding Path=EditCmd}” CommandParameter=”{Binding}” 
                Content=”Save” Height=”24″ HorizontalAlignment=”Left” Margin=”123,0,0,12″ 
                Name=”btnSave” VerticalAlignment=”Bottom” Width=”105″>
        </Button>
        <TextBox Height=”24″ Margin=”93,10,139,0″ Name=”txtFn” VerticalAlignment=”Top” 
                 Text=”{Binding Path=FirstName}” />
        <TextBox Height=”24″ Margin=”93,40,139,0″ Name=”txtLn” VerticalAlignment=”Top” 
                 Text=”{Binding Path=LastName}” />
        <TextBox Height=”24″ Margin=”93,71,139,0″ Name=”txtCity” VerticalAlignment=”Top” 
                 Text=”{Binding Path=State}” />
        <Label Content=”Relationship:” Height=”24″ HorizontalAlignment=”Left” Margin=”370,100,0,0″ 
               Name=”label1″ Padding=”0″ VerticalAlignment=”Top” VerticalContentAlignment=”Center” />
        <TextBox Height=”24″ Margin=”370,124,12,0″ Name=”txtRelationshipName” 
              
   Text=”{Binding ElementName=lvwInsuranceInfo, Path=SelectedItem.Relationship}” 
                 VerticalAlignment=”Top” />
        <Label Content=”Name:” Height=”24″ HorizontalAlignment=”Left” 
               Margin=”370,149,0,0″ Name=”label4″ Padding=”0″ VerticalAlignment=”Top” 
               VerticalContentAlignment=”Center” />
        <TextBox Height=”24″ Margin=”370,171,12,0″ Name=”txtName” 
                 Text=”{Binding ElementName=lvwInsuranceInfo, Path=SelectedItem.DepName}” 
                 VerticalAlignment=”Top” />
        <Label Content=”Age:” Height=”24″ HorizontalAlignment=”Left” Margin=”370,201,0,0″ 
               Name=”label5″ Padding=”0″ VerticalAlignment=”Top” VerticalContentAlignment=”Center” />
        <TextBox Height=”24″ Margin=”370,231,12,0″ Name=”txtAge” 
                 Text=”{Binding ElementName=lvwInsuranceInfo, Path=SelectedItem.Age}” 
                 VerticalAlignment=”Top” />
    </Grid>
</Window>

As shown above, the UI controls are bound to the corresponding properties of the ViewModel instance. Note also how the Save button’s command property is wired to handle its click event. Finally, the code to set the main window’s data context looks like this: public partial class MainWindow : Window
{
    public MainWindow ()
    {
        InitializeComponent ();
    }

    private void btnClose_Click (object sender, RoutedEventArgs e) {
        this.Close ();
    }

    private void Window_Loaded (object sender, RoutedEventArgs e) {
        this.DataContext = new InsuranceViewModel ();
    }
}

In fact, this is also the entire code-behind for our demo application! All it does is just set a ViewModel instance to the window’s data context. In fact, this can also be moved to XAML markup to do it declaratively and get rid of

Window_Loaded
handler altogether.


Just for the demo purpose, the ViewModel class fills itself with some sample data when instantiated as shown below.

public InsuranceViewModel () {
    FirstName = “Dave”;
    LastName = “Watson”;
    State = “NJ”;
    Dependents = new ObservableCollection<FDependents> ();
    Dependents.Add (new FDependents () {
        Relationship = “Spouse”,
        DepName = “Milla Watson”,
        Age = 33 });
    Dependents.Add (new FDependents () {
        Relationship = “Son”,
        DepName = “John Watson”,
        Age = 10 });
    Dependents.Add (new FDependents () {
        Relationship = “Mother”,
        DepName = “Marie Gold”,
        Age = 65 });

    EditCmd = new EditCommand (this);
}


 

If everything works fine whether you set the data context via code or markup, the output screen will be:


Making any of the top three text boxes empty, automatically disables the Save button:


The text boxes on the right are hooked to the selected item in the list view to let the user edit the selected dependent. WPF binding engine provides certain validation logic out of the box. In our demo, the Age property is numeric and in the screenshot below, you get a red outline around the text box when it is empty or have non-numeric values without requiring any extra code or configuration. By the way, this is nothing to do with MVVM, but thought would highlight some of the tiny benefits WPF gives free.


That’s it! Here is the recap of what we have discussed so far:

  1. MVVM is all about separation of business logic & UI separation in WPF and promoting loose coupling
  2. The code-behind contains no business logic (other than hooking the ViewModel if you choose to) with proper MVVM in place
  3. WPF’s Binding and Commands are the backbones for MVVM. Without them, it is very difficult to implement the pattern in a useful way.
  4. You follow simple steps to create a working ViewModel class:
    1. Let the ViewModel class expose properties based on what the UI shows
    2. Implement
      INotifyPropertyChanged
    3. Create custom commands for applicable user actions/control events by implementing
      ICommand
    4. Bind its properties/commands to control properties in the XAML markup
    5. ViewModel classes are easily testable now
    6. Changing UI in future is as simple as designing a new one and consuming the existing VM. In fact, the UX team can try many prototypes and get feedback from the business with real data
    7. Since WPF and Silverlight front-ends can share almost the same ViewModel the effort required to support one front-end in addition to the above is lesser than having to building from the scratch. The bottom-line is reusability.

In some cases your code-behind may end up with extra code around MVVM hook up and other plumbing but that’s ok as long as you do not write any code that otherwise can be moved to ViewModel.

Alright, another claim is that MVVM enables independent (without UI intervention) testing of VM and downstream business logic easily. Restating one of the attributes of VM, it is purely UI independent and hence you can test the VM like any other class. For example, below is a simple NUnit test fixture for the

InsuranceViewModel
class. Like the UI, the test fixture in all respect is yet another consumer of VM.

[TestFixture]
public class InsuranceInfoVMUnitTest
{
    [Test]
    public void TestVMInit ()
    {
        var vm = new InsuranceViewModel ();
        vm.PropertyChanged += 
            (s, e) => {Debug.WriteLine (String.Format(@”Property {0} value changed.”, e.PropertyName));};
        Assert.IsNotNull (vm.Dependents, @”Dependents collection not initialized.”);
        Assert.IsNotNull (vm.FirstName, @”First name failed to initialize.”);
        Assert.IsNotNull (vm.LastName, @”Last name failed to initialize.”);
        vm.State = “PA”// Should write out a debug message; check Debug window
        vm.FirstName = “”;
        Assert.IsFalse (vm.EditCmd.CanExecute(vm), @”EditCmd failed to check empty FirstName.”);
        vm.FirstName = “Bill”;
        vm.LastName = “”;
        Assert.IsFalse (vm.EditCmd.CanExecute(vm), @”EditCmd failed to check empty LastName.”);
        vm.LastName = “Rogers”;
        vm.State = “”;
        Assert.IsFalse (vm.EditCmd.CanExecute(vm), @”EditCmd failed to check empty State.”);
        vm.EditCmd.Execute(vm);
        vm.State = “CA”;
        Assert.IsTrue (vm.EditCmd.CanExecute(vm), @”EditCmd failed to check valid InsuranceInfo properties.”);
        vm.EditCmd.Execute(vm); // Save button click
        // Load current insurance info afresh & check for updated values
    }
}


 

Now that we have discussed MVVM at a reasonable level, lets us see the flip aspects of MVVM in WPF:

  1. MVVM requires extra code to be written; you have to implement a few interfaces and extend few base classes and all these would most probably take more time but the end advantages are many. It is better to invest upfront to save in future.
  2. For more sophisticated applications, you may have to write value converters to handle custom types in XAML markup.
  3. Some argue that ViewModel is the new code-behind and not a value adder when it comes to separation of concerns. This is motivated by the View (UI) delegating event handling to ViewModel class through command binding (
    ICommand.Execute
    method). This in a sense gives a feeler of having event handler methods in the ViewModel. Nevertheless, I am not against or favor of this point as it depends on the individual’s viewpoint.
  4. Out of the box, commands are available only to
    ButtonBase
    -derived controls,
     MenuItem
    , and
    HyperLink
    . For other controls, esp. selection controls such as combo box, list view, you have to resort to other ways (may be, I will cover this in a future post).

Model-View-ViewModel Pattern 101 (Part 2)

This is the continuation of my previous discussion on MVVM here.

With the advent of new designer tools such as Expression Blend, MVVM pattern suites WPF/Silverlight development very well. Expression Blend (or anything that produces WPF XAML) enables UX design and developer teams work independently, unlike early days of waiting for the UI to complete before the developers put their meat. Since both the teams work in parallel, there is a significant saving in the whole development effort. The most important advantage on the table is that the development team can now unit test their code with mock UIs before plugging the actual UI. Note that this mock UI is simply a test class that talks to ViewModel like a real WPF UI would do via property access and method invocation. Once the actual UI is ready, it’s just a matter of changing certain properties in the XAML (to hook to the ViewModel) and re-compiling it.

Let us look at the two WPF features that power MVVM:

Commands: In short, the Command pattern wraps an action to be executed on a target (yes, the same GoF pattern) independent of who triggered it. In the context of WPF, a Command is triggered by a control event (button click for example) with optional command parameters. Some of the aspects of the Commanding infrastructure are:

  1. Command source – The control that triggers the command. The source may disable itself if the command it can trigger cannot be triggered due to various reasons. You would have for sure noticed all the text editors disabling their Copy menu item, context menu and command/ribbon bar buttons when there is no text selected. Here, Copy is the command and the UI elements invoking Copy (menu item, command bar/ribbon button and context menu) are all command sources.
  2. Command target – The object/control the command execution logic depends on. In the text copy example above, the text box is the command target because the copy function works the properties (text selection) of the text box. If no text is selected, copy cannot work and hence the associated controls would be disabled.
  3. Command – The command itself with optional parameters required for executing the command logic. You might have also come across another term called ‘routed command’, which is nothing but a command with the ability to traverse up and down in the visual tree hierarchy (Routing is a topic by itself and won’t be discussed here).

Binding: A powerful feature to let UI controls automatically get data from an object and populate themselves instead of manually doing it. The binding infrastructure takes care of automatically updating the target whenever the source changes, vice versa or both (two-way binding). This is accomplished via event notification mechanism already available in .NET. The implying fact is that there should be a mechanism for the WPF’s binding engine to detect changes in the bound property data and pass those changes to the listeners. Binding can be used not just for properties but also for commands. The latter is required to delegate event handling logic from the UI to elsewhere (read ViewModel)! One important aspect of command binding is that it sets the binding scope which determines how far in the ancestor hierarchy a control can search for its command event handler.

These two form the backbone of the MVVM implementation, indeed. Despite a tiny description of Commands and Binding, both Silverlight and WPF have a strong infrastructure for Commands and Binding. I assume you have basic understanding of the both and the above only sets the context for MVVM.

I will get into some code and implement MVVM in WPF in my next due.