MVC vs. MVP vs. MVVM

An important FAQ. The answer actually depends on where the person is coming from. MVC is a fundamental pattern which has been tweaked quite a bit to fit into various platforms. For instance if you had asked anybody how to implement an MVC in ASP.NET (prior to release of ASP.NET MVC framework) you would get very different answers. So let’s start with basic. The common motivation behind all three is separation of concerns – cutting flab from UI (good for UI designers), swapping UIs (for instance windows to web), make UI conducive to Unit Testing, etc. Have a look at the below diagram, I have taken it from CAB documentation. Let’s dig into them.


MVC: Three components – View (your UI), Model (your business entities / data – that view is displaying) & Controller (contains the logic that alters the model state depending on the action triggered by UI – typically implementing a Use Case). It’s widely known that MVC is a compound design pattern (View and Controller have Strategy design pattern implementation, View itself can be a Composite pattern implementation & View and Model are synched through Observer pattern; for more details refer to GOF patterns). In MVC, Controller doesn’t know anything about View, and the idea is that a View can switch Controllers (for instance depending upon who has logged to the system) & a single controller can be used by multiple Views. View subscribes to the changes done to the model & hence both are sync from the state perspective. One of the disadvantages of MVC is that it’s difficult to unit test. Controller manipulates the data but how about asserting those changes from a view perspective. For instance, on click of a button you raise an event to controller, controller modifies the value in model, and this model state modification changes the font size / color in View. Unit testing this scenario is slightly difficult in MVC.

MVP: Again three components but the dependencies change (look at arrows in the above diagram). Over here we replace Controller with Presenter (one which presents the changes done in model back to view). The main difference between both is that in MVP Presenter refers back to the view while in MVC the Controller doesn’t. Normal pattern found here is to create a mock for the View (in terms of properties / events) & Presenter is injected with it. This makes the testing of View much easier & hence the Unit Testing aspect. Presenter here hence takes the responsibility of not only manipulating model but also updating the view. Of course, the implementations of MVP differ in real world in terms of complexity of the view. Some prefer keeping basic logic still inside view & taking complex logic in presenter, while others prefer keeping the entire logic in Presenter. Martin fowler describes 2 variations on MVP on these lines namely – Supervising Controller & Passive View described below.

A Passive View handles this by reducing the behavior of the UI components to the absolute minimum by using a controller that not just handles responses to user events, but also does all the updating of the view. This allows testing to be focused on the controller with little risk of problems in the view.

Supervising Controller uses a controller both to handle input response but also to manipulate the view to handle more complex view logic. It leaves simple view behavior to the declarative system, intervening only when effects are needed that are beyond what can be achieved declaratively.

MVVM: Model–View-ViewModel talks of creating a new model (in addition to your domain model). This model has fields and properties from the perspective of View typically a superset of domain model (as we understand that View has more data points in addition to model state being displayed). For instance, if View has a property IsChecked and Presenter was setting in classic MVP, in MVVM Presenter will have that IsChecked Property which View will sync up with (doesn’t it look like Strategy pattern has been replaced with Observer pattern 🙂 ?). So now a Presenter becomes more like a combo of – View Properties & Model properties which would be synchronized with View. So why not rename Presenter to ViewModel? Do that and you get MVVM (replacing ‘P’ with ‘VM’ in MVP). MVVM is attractive for platforms which support bi-directional view-model binding reducing the implementation effort. Also a minor tradeoff is ViewModel unlike Presenter can stand on its own for unit testing (Presenter normally requires a View’s interface). Martin fowler describes similar pattern called Presentation Model & Josh Smith captures MVVM implementation for WPF / Silverlight in this article.


ASP.NET MVC: So what has MVC got to do with ASP.NET MVC? First, Web application work on a different model. Here, user interacts with HTML in browser and send a request back to the server for processing (for client side Ajax you might go just for data). As the interaction is normally stateless, when the request comes back to the server we need to recreate our View, load the model back & manipulate both of them as required. There are 2 variations on how handle this recreation – Page Controller & Front Controller. Page Controller makes Page the decision maker – in this widely implemented pattern HTTP request is sent to specific to physical page on server (.aspx for instance) & the page in turn creates itself (builds the view from postback data), triggers the state manipulation (events in codebehind file) and model changes are made. As you see here, the distinction between View & Controller becomes blur & is little difficult to separate. This where ASP.NET MVC comes in. It behaves like a Front Controller – where Controller is the decision maker. Here all HTTP requests are mapped to methods on the Controller Class. Controller class recreates the model & view as required and does the manipulations. This makes unit testing easier as we can directly instantiate the front controller class & invoke methods on it to perform the assertions.

I can add code snippets to above explanations if you feel they would help you understand things better. I will look forward to your comments 🙂 .

WF DependencyProperty vs. WPF DependencyProperty

I had blogged about DependencyProperty in detail and its implementation in WPF. As it turns out WF has it own version of DependencyProperty which is also used nearly for the same purpose of Data Binding, Attached Properties, etc. I guess the MS teams were too busy back then in their own stacks and wanted to avoid any cross dependencies on each other. Hopefully these types would see a merger in 4.0 framework with consolidation of XAML; all moving entirely to a different assembly. Below are the different APIs currently available for WPF/WF frameworks:

System.Windows.DependencyProperty.Register(“Name”, typeof (dataType), typeof (parentDataType),
new System.Windows.UIPropertyMetadata(0, null, null), null); //def. value and callbacks

System.Workflow.ComponentModel.DependencyProperty.Register(“Name”, typeof (dataType), typeof
(parentDataType), new System.Workflow.ComponentModel.PropertyMetadata (
System.Workflow.ComponentModel.DependencyPropertyOptions.Metadata)); // type of property

Don’t they look like two departed brothers in Kumbh Ka Mela 🙂

Published XBAP access failing on IIS 7

XBAP projects normally have config files attached to them which point to WCF services. The problem with IIS 7 is by default it doesn’t allow any requests for .config files to pass through. To enable access for config files in IIS 7 you can go to Features view of your application’s virtual directory and double click on Request Filtering as shown below.


Over here you will find all file extensions listed. You will see that by default .config are not allowed. You can delete the same and recreate the .config file extension with Allowed set to true as shown below:


Hope this helps 🙂 .

ControlTemplate vs. DataTemplate vs. HierarchicalDataTemplate vs. ItemsPanelTemplate

If you don’t know what they are, then you need to go here first. 

Before we get into differences between them, let me show how one would typically use them. It’s a good practice that all your templates are embedded inside resources / styles. It makes your XAML centralized, shareable and easier to understand (a re factored XAML of sorts, waiting for ReSharper to include this refactoring 🙂 ).

Don’t Do:
                    <!– Your Data Template Goes here–>

        <DataTemplate x:Key=”myDataTemplate”>
            <!– Your Data Template Goes here–>            

<ListBox ItemTemplate=”{StaticResource myDataTemplate}” />

The above XAML holds true also for HierarchicalDataTemplate & ItemsPanelTemplate. But it won’t quite work for ControlTemplate, as ControlTemplate can be assigned to Template property of a class that inherits from ContentControl class, which ListBox doesn’t.

So the listbox code would typically look like this:

<ControlTemplate x:Key=”myControlTemplate” TargetType=”{x:Type ListBoxItem}”>
            <TextBox />

            <ListBoxItem Template=”{StaticResource myControlTemplate}” />            

But the problem with above snippet is, you are manually specifying item which is never the case in real world. Ideally you would like to bind ItemsSource Property of ListBox with some collection obtained at runtime from your data access layer. Solution to this problem is creating a style and binding it to ItemContainerStyle property of ListBox. By doing that you will be able to use ItemsSource for Binding & the ControlTemplate which is present inside the style will be applied to each binded item.

<ListBox x:Name=”myList” ItemsSource=”{Binding}” ItemContainerStyle=”{StaticResource myStyle}” />
<Style x:Key=”myStyle” TargetType=”{x:Type ListBoxItem}”>
            <Setter Property=”Template”>
                    <ControlTemplate TargetType=”{x:Type ListBoxItem}”>
                        <TextBox Text=”{Binding collectionPropertyName}” />

ItemsPanelTemplate is mainly used by controls inheriting from ItemsControl class for displaying their Items. ItemsPanelTemplate can be customized through ItemsPanel property of ItemsControl class or any class which inherits from ItemsControl.

<ListBox x:Name=”myList” ItemsPanel=”{StaticResource myItemsPanelTemplate}” />
<ItemsPanelTemplate x:Key=”myItemsPanelTemplate”>            
            <StackPanel Orientation=”Horizontal” />

The point of confusion is normally between selecting a ControlTemplate or DataTemplate. Normal saying goes as DataTemplate provides visualization to a business object while ControlTemplate does the same to a UI control. But in my project I see ControlTemplate used almost everywhere. Normally UI guys start creating screens while we are still giving shapes to our domain model (deadlines issues you see). Moreover, I feel one has to get slightly deep with WPF control properties to create an appealing professional UI.  So atleast here, we developers don’t quite mind giving a free hand to UI guys. We just go over to control templates residing inside styles & giving names of Business Object properties inside the bindings created by them. Also ControlTemplate triggers are based on UI control properties which is what UI team is often interested in. Few more differences are given here.

HierarchicalDataTemplate is an extension of DataTemplate with an additional ItemSource property. It is used to render hierarchical data in controls like treeview or menu. HierarchicalDataTemplate ends with a Data Template.

<HierarchicalDataTemplate DataType=”{x:Type Department}” ItemsSource=”{Binding Path=Classes}”>
            <TextBlock Text=”{Binding Path=DepartmentName}” />

<DataTemplate DataType=”{x:Type UniversityClass}”>
            <TextBlock Text=”{Binding Path=ClassName}” />

Hope the above helps you in getting started with WPF templates.

VTD Slides & Demos – Winforms WPF Interop

Dear All, thanks for being such a wonderful audience. For those who were new to Winforms & WPF I strongly recommend to wait for the session recording which should be available on VTD site in about a week time. I have uploaded my PPT & Demos here. Demos cover concepts like,

1) Using ElementHost in Winforms application
2) Using WPFControlLibrary in Winforms application
3) Using WindowsFormsHost in WPF application
4) Sharing DataSource across WPF / Winforms controls (INotifyPropertyChanged, BindingList, BindingSource)
5) Property Mapping from WPF to Winforms (Propagating Property Inheritance from WPF to Winforms)

Hope this would help you get started with your interoperability scenarios. Hum hain rahi pyaar ke phir milenge chalte chalte. Love you all 🙂 .

It’s a Hat-trick at VTD

Hat-trick is no longer restricted to cricket 🙂 . Tomorrow I will be presenting a session on “Making Winforms & WPF Work Together” at VTD. This will be my 3rd VTD back to back. First was in September & the second one in November. Ensure you mark your calenders. As always I assure you the value for your precious time. Do watch this space for the PPT & Demos. Catch you at VTD 8) .

Inside WPF’s DependencyObject & DependencyProperty

This is one of my older post, which I would like to copy here. WPF programmers (& also WF programmers) would have heard the names of these 2 classes. It’s quite easy to take these 2 classes for granted (unless you are into custom control or custom activities creation). The lines below provide some motivation from WPF perspective & also clearly differentiates between both classes. I found them useful, so thought of copying it here. Hope you find it too 🙂 .


If you have spent some time drilling into WPF you are bound to run into 2 classes – DependencyObject & DependencyProperty. They two together provide the base for underlying Property System of WPF. It’s well documented that DependencyObject is nothing but a glorified hashtable, but the same holds true for DependencyProperty too.

For e.g. have a look at following code:

public class Person : DependencyObject //CTRL + K + X -> Insert snippet shortcut for inserting Dependency Property
public static readonly DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof (string), typeof (Person));
public string Name
return (string) GetValue(NameProperty);
SetValue(NameProperty, value);

The function that caught me in the above code was DependencyProperty.Register – What the heck is that doing? On probing further I discovered that DependencyProperty maintains a Hashtable internally called PropertyFromName. PropertyFromName is where all the dependency properties of WPF are stored. A property is uniquely identified on basis of it’s name & owner. For instance if you try to register another property in the above code (may in a different class) with the same name & owner type (that is Person) you will get an ArgumentException. DependencyProperty also stores other attributes like default value of the property (e.g. every Person can have a default name called ‘Unknown’).
E.g. Person.NameProperty = DependencyProperty.Register(“Name”, typeof(string), typeof(Person), new PropertyMetadata(“Unknown”));

Let’s focus on DependencyObject now. DependencyObject itself internally maintains an hashtable. DependencyObject contains 2 important methods called GetValue & SetValue which are used to retrive values from the internal hashtable. The hashtable comes into play when you try to modify the default value of DependencyProperty. For e.g. the default name of every person is let’s say ‘Unknown’ & you are setting it to your name. So the value you are giving goes & sits inside the DependencyObject’s hashtable. Important thing to note here is in many cases the value may not be explicitly set by you but the value may be derived from surroundings. E.g. let’s say the creator of class Button has set it’s default background to white & you haven’t explicitly set the background but when you run the application you see that background color is black. Now this may be due to Operating System’s theme you have selected. Hence many developers refer to DependencyObject as a value engine.

So the question that comes to mind is why such complexity was required in first place? Answer is quite simple. If this properties weren’t dependency properties then would have been normal .NET properties allocated per instance. Dependency properties are created per type & can be customized if required (like per instance). So if your screen has 20 buttons you storage space for properties occupied is as good as for one button. Of course things can change if all the properties of buttons are modified for all 20 buttons which is a very rare scenario.

How about calling this a sparse storage design pattern 😀 ?

WCF Certificate Security with XBAP / IIS Issues

wsHttpBinding uses Message Security by default. But the default clientCredentialType is Windows. Now considering that your clients are going to access your application over internet, it makes sense to use Certificate / Username security. In my case I was using an XBAP in full trust and it was a more of fixed clients business scenario, so I thought of making use of the same certificates to provide secure transfer of data. Steps for doing the same are provided below:

1) Change clientCredentialType to Certificate (this would require you to customize wsHttpBinding) & specify the serviceCertificate in serviceCredentials of the web.config file. (N.B. The service can pick the certificate only from Local Machine and this can be the same certificate you are using to provide full trust to XBAP).

2) Next using Add Service Reference, generate proxy for the client. After generation you need to specify the location of the client certificate (this certificate would in Current User certificate store on client’s machine & different one from what we selected in step 1 – ideally used for authenticating client to service). This can be done by specifying new endpoint behavior on the client side.

3) As a final step in the client’s app.config file you need to change value:

<endpoint … >
      <dns value=”YourCertNameHere” />

Plus if you are using self issued certificates through (certmgr.exe), you will need enable PeerTrust in service’s web.config and client’s app.config (search for authentication certificateValidationMode and set it to PeerTrust)

<authentication certificateValidationMode=”PeerOrChainTrust” />

(N.B. If you hosting your service on IIS & running under ASPNET/NETWORKSERVICE account, you would have to grant rights to that certificate so that IIS can access it when required. This would require you to download FindPrivateKey (I found it here) and execute below commands:
1) findprivatekey My LocalMachine -n CN=localhost –a
2) Output – (C:\Documents and Settings\All Users\ApplicationData\Microsoft\Crypto\RSA\MachineKeys\
3) cacls “C:\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys\7b90a71bfc56f2582e916a51aed” /E /G ASPNET:R
(Change ASPNET in step 3 to NETWORKSERVICE – For Windows Vista IIS7))

XBAP + Application Download Error

Recently I was trying to access a published XBAP application in LAN. While try to browse to XBAP file it gave me a Application Download Error. After struggling for some time I found a solution that worked. I went to IE -> Tools -> Internet Options -> Connections -> LAN Settings -> Advanced & made an entry in – “Don’t use proxy server for addresses begining with”, 192.168.*. After a Refresh, things came back to normal 🙂 .

N.B. 192.168 – were the starting IP Classes assigned to the LAN I was working on, so they may be different for your environment.

One more error I had encountered was unable to load – .config file. If you are on IIS 7, one solution to it is given here (Search for IIS7 Restrictions and XBAP). There is one more link which is quite useful.

Other typical errors you might encounter are:

1) 403 Forbidden: couldn’t download .config file
2) 500 Internal Server Error: couldn’t download .dll file
3) 404 file not found – .dll / .config not found error
4) Protocol Violation Error, Section=ResponseStatusLine

For above of these, I request you to check the IIS Log files. Try to figure out the error from there. You can browse to the file per se that’s showing error (e.g. right click the config file or dll file & say Browse). Ensure this is working (e.g. config file get’s displayed as XML in browser, .dll file opens in a save dialog box, etc.). Check that Anonymous access is there for the web site / Virtual directory (if your security permits). Get rid of internet proxy if any is involved (as described earlier). If you are calling a WCF / Web Service ensure that both are in same domain or if possible on same server. WCF URL’s in the config file should not use localhost instead they should use LAN / WAN IP Address (simple but sometimes you may miss it 🙂 ). Fiddler is a great debugging tool which can be put in to use here. 

For 4th issue you can add following configuration to app.config of XBAP project

  <httpWebRequest useUnsafeHeaderParsing=”true” />

Well, I know for sure that you can loose your hair over XBAP deployment 😦 . If you have encountered other issues or resolved similar issues please do drop a line.