Wednesday, January 1, 2014

Troubleshooting data binding

We all know that DataBinding is one of the most powerful concept of WPF. So, today I thought to write something on how to troubleshoot data binding related issues while working with any XAML based application. Here I'll not talk about what and how data binding works, instead I'll jump directly on the relevant part. So, let's start by picking up the troubleshooting methods which can make developer's work bit easy.

Way 1: Using Visual Studio output window
Visual Studio provides high level information about binding which is sufficient to resolve very small problems like name mismatch, etc. Let's understand this along with a code snippet:
 <Grid>
        <TextBlock Text="{Binding  ElementName=label, Path=Hello, Mode=OneWay}"/>
        <Label Content="Welcome" Name="label"/>
  </Grid> 
Now open your output window and press F5, application will launch. In output window, you will notice that the message stating: 

System.Windows.Data Error: 40 : BindingExpression path error: 'Hello' property not found on 'object' ''Label' (Name='label')'. BindingExpression:Path=Hello; DataItem='Label' (Name='label'); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String') 

After reading the above message, it is very easy to identify and resolve the issue. Isn't it ??? 

Way 2: Using TraceLevel
TraceLevel is an AttachedProperty which was introduced with .Net 3.5. This adds the trace information to the output window of Visual Studio with detail level of None, Medium or High. To use this TraceLevel property, one extra namespace needs to be incorporate in XAML as:   
xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase" 
and add the TraceLevel to the binding as: 
<Grid>
    <TextBlock Text="{Binding  ElementName=label, Path=Hello, Mode=OneWay,diag:PresentationTraceSources.TraceLevel=High}"/>
        <Label Content="Welcome" Name="label"/>
</Grid> 

Way 3: Using Snoop
Snoop is the WPF utility which allows you to browse through the visual tree of a running WPF application. More details about snoop can be found here

Way 4: Debugging data binding using an converter
One can write a converter and put a breakpoint inside the convert method. Once this is done, the converter need to be setup in the binding. Let's have a look at the code: 

 namespace DebuggingDataBinding
{
    /// <summary>
    /// Converter to debug the binding values
    /// </summary>
    public class DebugConvertor : IValueConverter
    {
        #region IValueConverter Members

        /// <summary>
        /// ask the debugger to break
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Debugger.Break();
            return Binding.DoNothing;
        }

        /// <summary>
        /// ask the debugger to break
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Debugger.Break();
            return Binding.DoNothing;
        }

        #endregion
    }

    /// <summary>
    /// Markup extension to debug databinding
    /// </summary>
    public class DebugBindingExtension : MarkupExtension
    {
        /// <summary>
        /// Creates a new instance of the Convertor for debugging
        /// </summary>
        /// <param name="serviceProvider"></param>
        /// <returns>Return a convertor that can be debugged to see the values for the binding</returns>
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return new DebugConvertor();
        }
    }
} 
In above snippet, provide value will create an instance of converter and return it. Now the XAML binding to sue this extension will be as:
<Window x:Class="DebuggingDataBinding.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:DebuggingDataBinding"
    Title="Window1" Height="300" Width="300">
        <Grid Height="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=Height, Converter={local:DebugBinding}}"/>
 </Window> 

Way 5: Using ExceptionValidationRule
One can associate ValidationRules with binding objects. So, whenever exception is thrown while updating binding source property, ExceptionValidationRule class will take care of it based on how we specify our logic to react with these exceptions. Let's have a look at the code.

I have a class named Person as:
public class Person
    {
        private string firstname;
        public string Firstame
        {
            get { return this.firstname; }
            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    throw new Exception("First name cannot be null or empty");
                }
                this.firstname = value;
            }
        }
    } 
Now we need to associate a rule with the binding and that can be done using in-built class calledExceptionValidationRule and XAML code will be:   
<TextBox Height="30" Width="80">
    <TextBox.Text>
        <Binding Path="FirstName" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <ExceptionValidationRule />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox> 
Please note, once can always come up with their own validation rules. 

Bit on performance
  • Less converters can lead to good performance - If possible, use minimal converters because converters require boxing and unboxing. One alternative is to create a property in a ViewModel, do conversion related activity in getter and bind to it.
  • Binding.DoNothing -  This seems to be useful in the scenario where return value of a converter need not to interfere in the binding process. In such cases, FallbackValue can be used.
  • Data binding cheatsheet can be found here

Friday, December 20, 2013

Automatic Numbering for the Primary Key Column

Many of you might have come across an issue of Auto incrementing while working with database products. Truly speaking, recently I also came across one silly problem and thought of sharing it here.
Imagine that at some point of time, you might want to send your new data to a back-end database. If your application supplies the auto-increment values, then
  • what will the database do?
  • what if application receives duplicate values from different client applications?
The answer is that these auto-increment values are never sent to the database because the auto-increment column in the database table will provide a value whenever a new row is added. After each new row is added, the back-end database table generates a new-increment number and then your application will query the database to get the newly created number. Your application will then update its primary key number to the values that came from the database. This means that all the foreign key references will need to be updated as well.

Another problem, what happens if you add new rows in your application to generate auto-increment values of 1 to 100 and then send these rows back to the database table, and the table already has 10 rows???

When the first row is sent from your application, it has an auto-increment value of 1. The new auto-increment number created in the database will be 11. Your application queries for the 11 and tries to change the 1 to 11. Guess, what will happen here? Of course, an EXCEPTION will be thrown because 11 is already in your table.

The solution to this problem is, set AutoIncrementSeed to -1 and set AutoIncrementStep to -1. This will cause negative numbers to be generated; they won't conflict with the values coming from the database because the database doesn't generate negative numbers.

Hope the above small tip will save your lot of time in debugging the code to find the root cause. Enjoy learning !!! 

Saturday, December 14, 2013

Formatting strings in binding

Recently I get a chance for a code walk through of an WPF application in order to achieve better performance. So, during my review process, I came across this below code snippet:

  <WrapPanel>
        <TextBlock Text="{Binding Path=FirstName,Mode=OneWay}"/>
        <TextBlock Text=" "/>
        <TextBlock Text="{Binding Path=LastName,Mode=OneWay}"/>
    </WrapPanel>

If you will closely analyze this given snippet, you will definitely get a way to optimize it. Well, I am talking  about formatting the string as well as binding part.

As most of you are aware that we have a property named StringFormat since .Net 3.5 SP1. So, why can't we use this StringFormat for our binding too. If you want to change the above code to incorporate StringFormat, then it will something look like:

<WrapPanel>
        <TextBlock>
                <TextBlock.Text>
                    <MultiBinding StringFormat="{}{0} {1}">
                        <Binding Path="FirstName" Mode="OneWay"/>
                        <Binding Path="LastName" Mode="OneWay"/>
                    </MultiBinding>
                </TextBlock.Text>
        </TextBlock>
    </WrapPanel>

Now here one can clearly see the double benefit of writing such code. First benefit is, instead of using two bindings, one can be used and another benefit is instead of using three TextBlocks only one TextBlock can be used.

This may help in achieving performance especially when used as a DataTemplate of an ItemsControl with huge number of items.

Please note that {} part at the beginning is an escape sequence, otherwise XAML parser would consider { to be the beginning of markup extension.

Tuesday, December 10, 2013

Resizing TextBlock with resizing of window

When dealing with XAML, many of you might have came across resizing issues in which your control is getting resize but the text/image inside the control is not getting resize as per the window size(it can be other user control). So, to deal with this Microsoft provide us with a Viewbox control, in which user can set the resizing aspects as per the need and requirement. So, this article focuses mainly on the properties provided by Viewbox control with proper sample code and output. MORE...

Thursday, November 14, 2013

Safest way to use RaisePropertyChanged method - MVVM series 3 of n

Background

In my previous post on Simplest MVVM Ever, I gave the simplest overview of implementing MVVM. Now moving forward, I thought to extend my previous post by picking individual areas. And this time, I selected RaisePropertyChanged. All the developers working on XAML related apps are very well aware about the use of this RaisePropertyChanged. I am sure, most of us are also aware on where to use this. But does everyone aware about what is the proper way or let's say generic way to use it ??? Well, even if you are not aware, no problem. At the end of this post, you will surely take home a useful tip on using RaisePropertyChanged.

Introduction

As we know that MVVM provides a loose coupling methodology. At lot many places it is very useful to get benefit of such architecture, but at the cost of your alertness. Because when we are talking about MVVM, we usually says that ViewModel has no knowledge about View and properties are the way, who binds View and ViewModel to show the data on the UI. Here is the gotcha !!!
ViewModels implement INotifyPropertyChanged interface, so that the property changes in ViewModel can be passed onto View. Let's take a sample property, to understand in better way:
public string SelectedName
{
    get { return _selectedName; }
    set
    {
        if (_selectedName != value)
        {
            _selectedName = value;
            RaisePropertyChanged("SelectedName");
        }
    }
}
Point to note here is the hard coded name of the property "SelectedName" within the RaisePropertyChangedmethod. Now due to requirement change, one of the developer came and change the name of a property fromSelectedName to FirstName, and at the same time, he forgot to change the parameter of  RaisePropertyChanged method.  Now what will happen ???
This silly oversight will neither cause any compilation or run time errors, but our feature will simply not work. And such things are very difficult to detect until and unless there is a major break in functionality. So, now, how to get rid of such sort of issues???  

Tip comes here  

Instead of hard coding the property name, can't we go ahead and fetch the property name dynamically using Reflection APIs. Well, of course we can. 
Reflection.MethodBase.GetCurrentMethod().Name 
To implement it in better way, let's go ahead and create an extension method to read this property name as:
 public static string GetPropertyName(this System.Reflection.MethodBase methodBase)
{
    return methodBase.Name.Substring(4);
}
Here Substring method is required to get rid of 'get_' and 'set_' at the start depending upon where it is called. 
So, by using this extension method, one will be able to raise property changed events without concern that in future your property name might change.  MORE

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)
    {
        _action(parameter);
    }

    #endregion
}
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???  

Model 

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

ViewModel

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; }
        set
        {
            if (Student.FirstName != value)
            {
                Student.FirstName = value;
                RaisePropertyChanged("FirstName");
            }
        }
    }

    private string _selectedName;
    public string SelectedName 
    {
        get { return _selectedName; }
        set
        {
            if (_selectedName != value)
            {
                _selectedName = value;
                RaisePropertyChanged("SelectedName");
            }
        }
    }
    
    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. 

View 

Coming to view, by code behind is totally empty except for setting of DataContext as: 
public MainWindow()
{
    InitializeComponent();
}
And most of the UI related stuff is placed in XAML file itself 
<Window x:Class="SimplestMVVM.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SimplestMVVM.ViewModel"
Title="MVVM" Height="300" Width="300">
<Window.DataContext>
        <local:StudentsViewModel x:Name="ViewModel"/>
 </Window.DataContext>
<Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="0.878*"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
         </Grid.ColumnDefinitions>
                <StackPanel Grid.RowSpan="2">
        <ListView Name="ListViewStudentDetails" 
               Grid.Row="2" ItemsSource="{Binding StudentList}">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Name" 
                         DisplayMemberBinding="{Binding FirstName}"/>
                </GridView>
            </ListView.View> 
         </ListView>
        <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>
        </StackPanel>
    </Grid>
</Window>
MORE 

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.

    Disclaimer

    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.

    References
    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? http://lnkd.in/bdera7q

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