Saturday, November 9, 2013

Simplest MVVM Ever - MVVM series 2 of n

Continuation to my previous article on WHY and WHEN of MVVM, this time, I am going to tell something on how we can create a simple MVVM application with minimal complexities. I am writing this article for those, who just want to see quickly how MVVM works. It doesn't do anything fancy and uses some basic databindings and commanding stuff. This article will be helpful for all those who are looking for a quick example of how to hook the View to the ViewModel and how commands plays a role. 
Today if you will surf internet, you will came across 1000s of articles discussing on what is MVVM and what are the major building blocks of it. So, I am going to repeat the same crazy thing again. But definitely, I'll brief you about major building blocks in layman, in order to make it easier to understand for beginners. Excited, eh ??? 
Layman introduction of building blocks  
So, let's quickly start with three main layers of MVVM.
  • Model - Model contains the classes which are similar to real world entities like Product, Customer, Student, Invoice, etc. It encapsulates business logic and data. Please note, Model classes do not directly reference view or in other way, Model classes have no dependency on view as how they are implemented. Technically speaking, Model classes are used in conjunction with a service or a repository that encapsulate data access.
  • ViewModel - Main purpose of ViewModel classes is to expose data to the view. It includes presentation logic and can be tested indepedently of Model. Similar to Model, ViewModel never reference View but it exposes properties and commands to bind the View data. In essence, ViewModel acts as a coordinator between View and Model.
  • View -  View deals only and only with appearance which one sees on screen. As a best practice, there should be no logic code in View classes, which need to be tested by unit test. In simple words, View's are meant only for UI visual behavior. 
I hope, till now, you might have got an idea of what is the responsibility of View, ViewModel and Model. Well, now before jumping onto coding part, I would like to brief you about some other points also, which needs to be handle for better and cleaner implementation of MVVM. 

Important components of any MVVM app

There are two main components which plays very vital role in implementing any application with MVVM. The first one is base class for ViewModel and second one is ICommand interface.
Base Class - There is some common stuff which is required for each and every ViewModel. So, in order to follow the good design, those common things should be placed in a base class and further this class can be derived by various ViewModels. Now question is, what this base class should contain?
This base class contains the implementation of INotifyPropertyChanged interface. As I mentioned earlier that, ViewModel cannot reference View directly. So, this interface bridges the gap between two and allows the messages to be passed to the View. The sample implementation of INotifyPropertyChanged is: 
public class ViewModelBase:INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;
    protected void RaisePropertyChanged(string prop)
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(prop));
Please note, the above snippet is the basic one. So, if required, it can be expanded in various ways like addition of various validations like property name check, etc.
Well, let's move to ICommand interface.

ICommand interface - This interface provides very useful methods like Execute and CanExecute, which gives full control on commanding part. Commands are used by View to interact with ViewModel. Sample code is:
public class DelegateCommand : ICommand
     private Action<object> _action;
     public DelegateCommand(Action<object> action)
         _action = action;

    #region ICommand Members
    public event EventHandler CanExecuteChanged;
    public bool CanExecute(object parameter)
        return true;

    public void Execute(object parameter)

I hope, this much knowledge is enough to proceed with simple MVVM example. 

Example scenario  

This is the example of Student entity and to keep it simple, I am taking only FirstName of a student. The list of students will be displayed on the screen. If user will select student name from the list and clicks on given button, then the selected name will be displayed in the textbox shown below. Isn't it simple???  


As I told, my model class is very simple here with 2 lines of code: 
public class Student
    public string FirstName { get; set; }


This class is bit complex than our Model. First let's have a look at the below snippet, then I'll talk more on it: 
public class StudentsViewModel:ViewModelBase
    public Student Student { get; set; }
    public ObservableCollection<Student> StudentList { get; set; }
    public string SelectedStudent { get; set; }

    private ICommand _updateStudentNameCommand;
    public ICommand UpdateStudentNameCommand
        get { return _updateStudentNameCommand; }
        set { _updateStudentNameCommand= value; }

    public string FirstName
        get { return Student.FirstName; }
            if (Student.FirstName != value)
                Student.FirstName = value;

    private string _selectedName;
    public string SelectedName 
        get { return _selectedName; }
            if (_selectedName != value)
                _selectedName = value;
    public StudentViewModel()
        UpdateStudentNameCommand = new DelegateCommand(new Action<object>(SelectedStudentDetails));
        StudentList = new ObservableCollection<Model.Student> 
                new Student { FirstName = "Bruce" },
                new Student { FirstName = "Harry" },
                new Student { FirstName = "Stuart" },
                new Student { FirstName = "Robert" }

    public void SelectedStudentDetails(object parameter)
        if (parameter != null)
            SelectedName = (parameter as SimplestMVVM.Model.Student).FirstName;
You might have notice that, we are inheriting ViewModelBase class, which provides the implementation ofINotifyPropertyChanged. Here I am exposing properties like FirstNameStudentList, andUpdateDetailsCommand which view can bind to. 
Well, let's take this one-by-one.
  • FirstName - This property is used to bind individual items of my ListView
  • StudentList - This property contains the list of first names and is set as a ItemSource of my ListView  
  • UpdateDetailsCommand - This property returns an ICommand using DelegateCommand class. This can be bind to anything like button press or key press. I hooked this command to my methodUpdateStudentDetails on button press, in order to update the text. 
That's all of the viewmodel. Now we can proceed for UI drawing. 


Coming to view, by code behind is totally empty except for setting of DataContext as: 
public MainWindow()
And most of the UI related stuff is placed in XAML file itself 
<Window x:Class="SimplestMVVM.MainWindow"
Title="MVVM" Height="300" Width="300">
        <local:StudentsViewModel x:Name="ViewModel"/>
            <RowDefinition Height="0.878*"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <ColumnDefinition Width="Auto" />
                <StackPanel Grid.RowSpan="2">
        <ListView Name="ListViewStudentDetails" 
               Grid.Row="2" ItemsSource="{Binding StudentList}">
                    <GridViewColumn Header="Name" 
                         DisplayMemberBinding="{Binding FirstName}"/>
        <Button Command="{Binding UpdateDetailsCommand}" 
          CommandParameter="{Binding ElementName=ListViewStudentDetails,Path=SelectedItem}"  
          Content="Update Text"/>
        <TextBlock FontWeight="Bold" Text="Selected student is: ">
          <Run Text="{Binding SelectedName, Mode=TwoWay}"/></TextBlock>

Monday, October 28, 2013

Why and When of MVVM - MVVM series 1 of n

Developing software is HARD. In fact, I would say, it's very HARD. Patterns and Architectural Structures help, but... it’s still hard. Like any other architectural structures, MVVM is also a structure with a set of guidelines and NOT a set of rules.

In the past few months, I came across various forums and online discussions, where people often ask "Why should I use MVVM? It seems like it complicates things" and I realized that MVVM is very difficult to learn for beginners who have very little knowledge of design patterns and frameworks.

As of today, if you will search MVVM in any of the search engines, you will get lot many articles written by the extremely knowledgeable through to the novices, and it is really hard to sort the wheat from the chaff.

Apart from this, there are lot of resources which mention few points and miss out others, which may be very conflicting for those beginners as well as for some experienced programmers. I'm not going to call them bad programmers, in fact they could be good programmers or say, they could be great programmers. Even if you are bad programmers, don't worry, I am not going to hang you for it.

Well, jokes apart. Regardless of all arguments, today I am not planning to introduce philosophy, but my plan is to put all the relevant concepts together in a single post, to make MVVM simple to understand and straightforward to implement. MVVM is far simpler than people make it out to be.

The most popular reason many developers put forward for MVVM is that "its main purpose is to do unit testing for presentation code". To some extent, this is true but this is not the only reason one should invest in MVVM. There are number of benefits this structure brings to WPF, Silverlight, Windows Phone as well as Windows Store application development process. Let's figure out the need of MVVM in layman language, which will help everyone to understand the concept in a much easier way:
  • Do you have a team for developer, designer and tester, and want all of them to work simultaneously on the same project or module?
  • Do you want to have a reusable components within the project or organization?
  • Do you want your UI and Presentation logic to be loosely coupled?
  • Do you want independent unit testing of your Presentation logic?
  • Do you have frequent changes in your UI due to requirement change?
  • Do you want reusable code between WPF, Silverlight, Windows App or let's say you want to share your code between more than 1 type of applications? (Please note: This is not 100% sharing of code, but yeah you can say, it is close to 90%. I would say, it is better to have something, rather than nothing. Isn't it ?)
Well, if you answered, any of the above questions in YES, then we can go for MVVM. The list is not only this much, there are bit more benefits around MVVM. I have drawn the below list from several discussions, blogs, presentations as well as with my experience. So, let's gear up and have a look at those benefits:
  • The rousing dynamism behind using MVVM is the XAML based apps, which evolve around very nice concepts of databinding, commanding, dependency properties, etc.
  • MVVM provides proper layering of the view and the data. The data is not stored in the view but the view is only and only used for data presentation. View need not to be aware as from where and how the data is coming. So, even if our business logic is changing n number of times, it will not at all impact our view. 
  • Concurrent development – Other advantage of using MVVM is that during the development process, developers and designers can work more independently and concurrently on their components. The designers can concentrate on the view, and if they are using Expression Blend, they can easily generate sample data to work with, while the developers can work on the view model and model components.
  • SoC (Separation of Concern) - MVVM help us to achieve SoC, by putting presentation logic into ViewModel. MVVM is not an exercise to remove all the code from your XAML code behind files. Instead, MVVM intends to separate the logic you need to access and interact with your data from the logic you need to interact with your UI. For example, loading your data, validating your data, manipulating your data, and saving your data – that’s all part of the View Model. Conversely, running animations, responding to gestures, and adding the blink that makes your app stand apart – that’s part of the View. Beginners, please note, ViewModel is not the code-behind file. It is a separate class for writing UI related logic. I will touch more upon this, in my upcoming posts.
  • Loose Coupling - By using code-behind approach, it is very easy to create tightly coupled UI elements, but that sounds really very bad. At the same time, tightly coupled approach will lead to huge time-to-market because everything needs to be in sequence as developer and designer are totally dependent on one-another to finish their task. Creeping logic into your code behind – it is not rare for developers to relish the easiness of double-clicking Visual Studio’s designer and allowing a click event handler be created. MVVM guidelines will help developers/designers to write much more cleaner code in a very loose coupled way.
  • MVVM provides the ability of a developer and a designer to work on the view independently without risk of corrupting the other's work. In MVVM, no matter what the designer does to the view, the ViewModel code is untouched. And same is the reverse, no matter what the developer does to the ViewModel, the View is not affected. Isn’t it amazing???
  • Design time data support is one of the features I like the most. Once UI is ready, designer can test the UI by using any of the supported designer tools. One of the commonly used tools Expression Blend, in which the designers can test the UI with sample data and even simulate a fully functional data binding scenario.
  • Multiple views: MVVM is very well known for flexibility and loose coupling. The same ViewModel can be presented with multiple views. For example, if you want to show different-different type of UIs based on the user role, then it is really nice to have bonus from the MVVM. In this case, all the UI will have almost the same business logic and only the data representation is different. So, a single ViewModel can serve multiple views.
  • Automated unit testing: Separation of this view/logic separation also greatly improves automated unit testing of the presentation logic. One of the primary benefits of using MVVM is the unit testability of the codebase. Traditionally, software was developed with event handlers embedded right in the codebehind of the presentation. This tightly coupled approach of view to business logic can easily result in code that is difficult to maintain. With the MVVM and unit testing in place, the codebase can remain robust over the lifetime of the software, and the intent of the developer can be well documented in the unit tests which are written (so long as unit tests are kept up to date).
  • It is very much easy to change view without messing up with ViewModel due to loose coupling.
  • Maintainability - Why does maintainability matter? Maintainability is not the inverse of complexity. That’s because complexity can be controlled by following good patterns and architectural guidelines like MVVM. But without good patterns and guidelines, complexity is the logarithmic multiplier to headaches and troubles. I never mind picking up on a project that is well organized.
  • I hope, by this time, you might have got an idea about all the benefits that MVVM provides. Now, let’s check on when to use this useful structure.

    When to Use MVVM

    Now the biggest question is WHEN to use MVVM. Lot of people think that MVVM is what we use all the time. But when you are building a very small app, like a one page or a two page application, it might make more sense just to do things like an ad-hoc way of building an application, where you pick the XAML, put in the project, hitting some services, hooking up some events and pushing information on to your UI page, just manually. That is perfectly fine while dealing with small application. But where MVVM really comes in handy is, when we start building large applications, in which we have several different pages, where we need to manage data structures.
    While doing internet surfing, I found a statement which states, "MVVM only makes sense for extremely complex UI", or "MVVM always adds a lot of overhead and is too much for smaller applications". The real kicker was, "MVVM doesn't scale". In my opinion, statements like this speak to knowledge and implementation of MVVM, not MVVM itself. In other words, if you think it takes hours to wire up MVVM, you're not doing it right. If your application isn't scaling, don't blame MVVM, blame how you are using MVVM. Binding 100,000 items to a listbox can be just silly regardless of what pattern or practice you are following.
    Conclusion is, it’s Not All That Different and it’s Not That Hard. MVVM is, without question, one of the best things to ever come out of XAML development. MVVM separates the logic necessary to intermingle with the data from the logic necessary to intermingle with the UI. Where together, it makes a jumbled mess, separating it makes a sophisticated approach that is more effortlessly maintainable.


    So the quick disclaimer: This is MVVM as I know it, not MVVM as a universal truth. I’m not saying this is all you’ll ever need to know about MVVM, I’m saying if you know this, you can benefit from MVVM on any non-trivial application, while you’re learning more. I encourage you to share your thoughts, experiences, feedback, and opinions using the comments. If you feel something is incorrect, let me know and I'll do my best to keep this post updated and current.

    Ending Note

    MVVM is neither a template nor has any class. But there are plenty of conventions and plenty of framework candy to help MVVM implementations sail simply. XAML developers love MVVM, in fact, MVVM was invented by the original WPF creators. To that end, MVVM is lightweight, simple, and easy to learn. Best part is, it can be used with Silverlight, WPF, Windows Phone or any other XAML based application.

    Jeremy's blog

Thursday, October 17, 2013

Microsoft Tech Days November 6 - 8

Tech.Days Online – November 6-8: All the sessions and an interview with Steve Ballmer. Have you registered?

This three-day virtual event will be packed with technology updates by expert presenters from Microsoft (UK and Corporate), the Microsoft MVP Community, customers and special guests.

Wednesday, October 16, 2013

Best Practices for ORM

Although everyone puts their complete effort to develop the best software, sometimes bad things happen. But to be on safer side we can take some precautionary measures. Well, today I want to share some of the best practices which needs to be followed while dealing with any ORMs (Object Relational Models). Most of these are common among many of the relational databases.
  1. Exception handling: One should handle only those exceptions which need to be handled, and let all others pass through. For example, if you want to handle a connection issue you should do this by catching the specific exceptions, but don't use a catch all on Exceptions with the clause "just in case" because it may lead to high performance issues.
  2. USING: As many of us know, that USING automatically handles dispose functionality. But this statement doesn’t work all the time, especially in the case of database connections. If you want to try it out, then run some overnight processes using windows services. Although USING handles it most of the time it is always a good practice to close database handles/connections manually.
  3. Prefer compiled LINQ queries: Compiling a query once and executing it several times can lead to high performance gains. Such queries are useful, especially when the same query needs to be accomplished numerous times for innumerable parameters. The syntax for that is: MORE...

Wednesday, September 25, 2013

New Features in Vistual Studio 2013 Release Candidate

It has been great movement, great work done by VS team for making easy to use Visual Studio. There has been lot of new features in Visual Studio 2013 preview, which has some very cool features in XAML, intellisence, goto definition and many more. But in RC, most of these features are extended. Today I'll try to cover as much as possible about all these new features. So, let's start by taking them one-by-one.

1) Intellisence in XAML - Earlier versions of VS were pretty cool but I hope, whoever working in WPF would have surely miss intellisence feature. But in RC, that is no more a limitation. So, if we let editor know where the data is, it will help us out like a friend and will make our work easier. VS2013 rc supports intellisence for DataBinding and Resources. Let's have a look of this feature in below screen shot:

Intellisence for DataBinding


Intellisence for Resources

2) Go To Definition in XAML - This new feature in available in VS2013 RC on right click of relevant object or by pressing F12 key in XAML. If you are pressing F12 on built in control, then it will pop-ups an Object Browser. This feature works for any valid user defined objects as well as for User controls. Below screen shot will give you better insight of the feature.

3) Insert snippet - Another cool feature is "Insert snippet...". If you will right click on XAML file, you will get this new feature in context menu. So, if you have any snippet, you can insert it or you can use any built-in snippets.
4) Intellisence matching - Let's say instead of typing DockPanel, you typed ockPanel. Well, from now onwards this will be taken care by VS2013. It will autmatically detect ockPanel as DockPanel. You can also type by lowercase and it will be automatically rectified by editor. It's not 100% matching, but yeah, it's still very helpful. Isn't it cool? Let's have a look at below figure for better understanding.

5) Refactoring - VS2013 RC also provide us the refactoring capabilities. Let's say, you want to change your Stackpanel to some other container. In this case, as soon as you will change starting or ending node, the other one will automatically get changed. This is one of the awesome feature, which reduces lot of typing.

6) Type Script - Another major enhancement is done in the area of Type Script (TS). Hope most of you are aware of TS. When you build your application, TS code automatically gets converted to JavaScript code. As TS is very easy to write, one can write code in TS and later get it converted on application build. To check out this enhancement, you can create a web application and get this Type Script option on right click of Scripts folder or in 'Add New Item' dialog. This feature was available in VS2012, but instead of integrated version, it asks you to download from Nuget or from But in VS2013 RC, one need not to download any external tool because this is built with the product itself as shown in below figure. The good thing is, VS2013 supports, intellisence for type script too.

7) Peek Definition - This is the new capability, which was added in Visual Studio 2013 preview. It allows you to view the other source file from your opened source code file. Let's understand this in another way and forget about this Peek Definition feature. With current editions of Visual Studio, if one want to see the information about particular method or class or any object from our current file, then only two options are available as either by using F12 or by using Go to Definition. Now problem here is, if the file is very huge then there are very high chances that user will loose the context or might forget where he/she was. So, Visual Studio team came up with a very brilliant idea of showing the object's information in the current window itself as shown below. Let's say developer wants to see the information about Employee class, then -

Here you might have noticed that being in the same window, user is able to view the source code of another object via an inline window. Infact, you can go further down in a nested way and can go back and forth among those nested windows also.

Another best thing is, user can also do code modification in these inline window and similarly, there are little other optimizations are done around the coded window.

8) CodeLens capability - If your Visual Studio 2013 is connected to Team Foundation Server (TFS) then you will get lot of additional features which can help developers as well as reviewers to ease their task. So, let's look at the source code in VS2013, you will find a small header at the top as shown below:

In above screenshot, I have a function named BasicEmployeeViewModel which has 5 references, 3 unit test cases. Now if you will click on references, it will show you all the references as:

By clicking on any of the references above, you can jump on to that particular part of code.
Now let's quickly jump on to another screenshot for unit test case:

By clicking on Run All, developer can run all the unit test cases at once. So, whenever you are making a change to your code, at the same time, you can run your unit test cases also.

The third part of codelens is available, only and only when your Visual Studio is configured with TFS. This part of codelens says as who has last modified this method. Let's see below screen shot:

Here developer can identify the person, who has last touched this method. This feature is also available at class level also. And in above figure, one can also get to know about the number of changes and what all the changes are done as shown below:

One more fabulous thing is, if you want to connect to any of the authors listed above, then you can click on that icon (orange square) and can communicate with him or her. If require, you can chat or e-mail to that concerned person. Definitely, here you will need a Lync integration ;)

9) Addition of Charts in TFS- There are few enhancements done in web interface of TFS. Below is the screen shot of web interface 2013 RC.

As part of release candidate, a new Chart capability is added on Queries tab as shown below:

This is a web based chart and one can select the chart of the choice from the given list as Pie chart, stack chart, etc. Now on click of queries, you will get the list of all the assigned items. As of now, only one item is assigned to my name, so only 1 is listed here as:

Now, when you will click on Charts, you will get the corresponding chart with all the items assigned to you. You can also select the group items for which you want to create a chart and it seems to be very flexible. Below shown is the Pie chart -
10) Addition of Features in TFS - One more feature is added into Backlog management as below:

Feature can be think of as one higher level abstraction. So, let's say you have one or more features, backlogs, then you can sort them by categories and can do lot more than this.

11) Others - 
Apart from all above. there were lot of major enhancements done in Office365 to host LoB apps in much more easier way. To meet this goal, a new template is added for building business apps having lot of plumbing done. This is not a 100% business app, but we can say, it's a good start.

Hope above list of features gave you a gist of Visual Studio 2013. So, let's wait for the release of VISUAL STUDIO 2013 :)

Thursday, September 12, 2013

Visual Studio 2013 RC is available for download

Visual Studio 2013 Release Candidate is available for download now. This release includes new tools for line of business applications, Web applications, games, mobile devices, services and of course applications targeting our latest platform Windows 8.1. With the Visual Studio 2013 Release Candidate (RC) and Windows 8.1 RTM for MSDN and TechNet subscribers, developers now have everything they need to start building and testing  the next generation applications for the Windows Platform. More...

Wednesday, September 4, 2013

WPF Error: IOException - Cannot locate resource

Recently I worked on a WPF application which supports localization using LocBAML tool. I created a sample application, having a very simple UI, consist of a button inside a window. Here I am assuming that most of you are aware on how to generate satellite assemblies. So, quickly coming to the point, when I build my application, build was successful. But when I launched, my application crashed with reason stated as IOException :(

After spending almost an hour, I came to know that it was due to Culture settings. Let's have a look at my code first:

Apart from this above code, I also updated my project file (.csproj) for development language so that my satellite assembly contains the neutral language resources. Following line was added in the project file:

Apart from this, I did nothing special in my app. After hitting my head on msdn, I got an idea on why culture changes was causing an exception.

Well, no need to get panic. Solution is pretty simple. Let's move ahead and  open your file and uncomment below line:
[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]

After this minor change, we are good to go.
By uncommenting this line, we are telling runtime that culture information needs to be read from satellite assembly.

Hope, this tip will save your time :)