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 3 is separation of concerns, cutting flab from UI (good for UI designers), swapping UIs (for instance windows to web), make UI easy for Unit Testing, etc. Have a look at the below diagram, I have taken it from CAB documentation.

MVCMVP

MVC: Three components – View (your UI), Model (your business entities / data – that view is displaying) & Controller (contains the logic that alters the model depending on the action triggered by UI, typically implementing a Use Case). It’s widely known that MVC is a compound pattern (View and Controller have Strategy implementation, View itself can be a Composite implementation & View and Model are synched through Observer). In this case 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 data 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, and controller modifies the value in model. This value modification changes the font size / color in View. Unit testing this scenario is slightly difficult in MVC.

MVP: Again three components. But dependencies change (look at arrows in the 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 Presenter refers back to the view while Controller doesn’t. Normal pattern found here is to create an abstraction of the View (in terms of properties / events) & Presenter refers to it. This makes the mocking 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 how much thin the view is, 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 normally adds additonal properties from the prespective of View (as we understand that View has controls in addition to data which it’s displaying). For instance if View had 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?). 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. MVVM is attractive for platforms which support bi-directional binding with less effort. Also a minor tradeoff is ViewModel unlike Presenter can stand on its own (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.

MVVM

ASP.NET MVC: So what has MVC got to do with ASP.NET MVC? First, Web works 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. Make Page the decision maker – in this widely implemented pattern HTTP request is specific to physical page on server (.aspx for instance) & page in turn creates itself (builds the view from postback data) decides what model it needs and triggers the manipulation (events in codebehind file) it requires. As you see here the distinction between View & Controller becomes blur & is little difficult to separate. This where ASP.NET MVC comes in which 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 🙂 .

Advertisements

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:

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

//WF
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.

iis71

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:

iis721

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:
<ListBox>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <!– Your Data Template Goes here–>
                </DataTemplate>
            </ListBox.ItemTemplate>
</ListBox>

Recommended:
<Window.Resources>
        <DataTemplate x:Key=”myDataTemplate”>
            <!– Your Data Template Goes here–>            
        </DataTemplate>
</Window.Resources>

<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 />
</ControlTemplate>

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

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”>
                <Setter.Value>
                    <ControlTemplate TargetType=”{x:Type ListBoxItem}”>
                        <TextBox Text=”{Binding collectionPropertyName}” />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
</Style>

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” />
</ItemsPanelTemplate>

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}” />
</HierarchicalDataTemplate>

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

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
{
get
{
return (string) GetValue(NameProperty);
}
set
{
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 😀 ?