19 November 2014

MVVM: Binding ListBox item double click event to a command

With intention of having 'no code' in code behind file, we often invest lot of time in finding how to invoke a command in your ViewModel whenever a UIElement raises an event. I certainly invested couple of hours googling.. binging for readymade answers. I couldn't find a satisfactory answers (may be I am poor in using right keywords ). But, with help of couple of posts in sites like StackOverflow & MSDN, I arrived at this very simple approach.

Below is my ViewModel which has a collection called Cities which I will be displaying in a ListBox in my View. My ViewModel has a command called ItemSelectedCommand which should be incoked when user double clicks on city.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/// <summary>
/// ViewModel for CityView
/// </summary>
public class CityViewModel : ViewModelBase
{
    /// <summary>
    /// Command that responds item double click event.
    /// </summary>
    public DelegateCommand ItemSelectedCommand { get; private set; }

    /// <summary>
    /// Gets or sets the selected city.
    /// </summary>
    public string SelectedCity { get; set; }

    /// <summary>
    /// Gets the list of cities.
    /// </summary>
    public List<string> Cities { get; private set; }

    /// <summary>
    /// Initializes new instance of <see cref="CityViewModel"/> class.
    /// </summary>
    public CityViewModel()
    {
        ItemSelectedCommand = new DelegateCommand(OnItemSelected);
        Cities = new List<string>() { "Bangalore", "New York", "Sydney", "London", "Washington" };
    }

    /// <summary>
    /// This method is executed when user double clicks on a city.
    /// </summary>
    /// <param name="sender">Unsed Parameter.</param>
    private void OnItemSelected(object sender)
    {            
        //Do the processing you need
    }
}


And here is the XAML

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<ListBox HorizontalAlignment="Center" ItemsSource="{Binding Cities}" SelectedItem="{Binding SelectedCity}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}">
                <TextBlock.InputBindings>
                    <MouseBinding Gesture="LeftDoubleClick"                                           
                                  Command="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=DataContext.ItemSelectedCommand}"/>
                </TextBlock.InputBindings>
            </TextBlock>
        </DataTemplate>
    </ListBox.ItemTemplate>                  
</ListBox>


I hope there is no need to explain the code and I hope you enjoyed reading this :)

4 September 2013

A look at extension methods and method overloading

Extension methods are a great way to inject our own methods into some other classes which greatly improve the extension of functionality, code re-use etc. Everything is well and good. However, we often miss some important details which might frustrate us. One such thing with extension methods is - CLR always chooses the closest method than closest match when an overloaded extension method is defined. Confused? Hmm... Let me take you directly into some code.

Below is simple class hierarchy.

class Parent {}

class Child : Parent {}

class GrandChild: Child {}

Very straight forward, isn't it? Now let me create a business class as below,

class MyClass
{
   public void Display(Parent objA) //------------------------------- (A)
   {
       Console.WriteLine("I am not an extension method");
   }
}

And now let me define an overladed extension method for MyClass,

static class Extensions
{
   public static void Display(this MyClass m, Child c) //-------------(B)
   {
       Console.WriteLine("I am an extension method");
   }
}

Ok. Done with setup. Before going further, you might want to have a relook at above classes and their relations. Anyways, below is my consumer class wherein I want to create an object of MyClass and call Display on it.

class Consumer
{
    public static void Main()
    {
       Child child = new Child();

       MyClass obj = new MyClass();
       obj.Display(child);
    }  
}

So, Could you guess what would be the output of above code? From our OOP and C# knowledge we tell that it will call extension method Display because it exactly matches the caller signature. Right? However, that's not correct. In this case, CLR prefers non-extension method (A) over extension method (B) even though the (B) perfectly matches caller's signature. It means, CLR picks the method 'Display' which is inside MyClass than the extension method 'Display' which is outside of MyClass.

Now just comment out Display method inside and run the code and  this time the extension method is called. This perfectly makes sense because when a method is called, CLR first search MethodInfo table of the class on which the method is being called. If it find a multiple method definitions in the same class, it chooses the best match. If it doesn't any entry, it will search up the inheritance hierachy. If it doesn't find any match, then it will look for any extension methods.

I hope you enjoyed reading this post and also might save you some time  when you encounter similar issues related to extension methods.

3 April 2013

MVP of the year

On  Thursday, January 24, 2013, I was a surprised to see my inbox that I am awarded as MVP of the year 2012. I am one among the 32 people awarded as MVP of the year and only person from India. It feels great to receive such a great award. Here is a official site that tells the story,

Developer MVPs of the Year

Thank you Microsoft for such a great honor. I also thank my MVP lead Tanmay Kapoor and Biplab Paul for their support.
 

30 September 2012

Creating RCW Interops from ActiveX (OCX) Controls

Many times we need to use ActiveX controls (ocx) developed in VB6 or C++ in our .NET applications. As you might aware of that, we can't directly use ActiveX components in .NET application. So, we need to create wrapper assemblies around the ActiveX components which we call Runtime Callable Wrappers as I have already talked about that in my previous posts. I am not going to discuss details of RCW, but I will show how to generate the RCWs.
 
You can generate RCW in two ways
1. Using Visual Studio
2. Using Tools TlbImp.exe and AxImp.exe.
 

Using Visual Studio to generate RCW:
This is the simplest way of generating RCWs. Then in your project, open the toolbar, right click on it and select 'Choose controls'. Browse the .ocx file and click OK.
 
 
Now open the 'obj' folder present inside the project folder and you will see two interop dlls are generated namely AxInterop.<FileName>.dll and <FileName>.dll. For example, if the control name is MyControl.OCX then generated assemblies will be AxMyControls.dll and MyControls.dll. The prior one contains the visible components of the user control that can be placed on the form. And later one contains the types.
 
 
 
Using Tools to generate RCW:
Above method of generating RCW fulfils most of the times. However, if you want to have some control over how the interops are generated like default namespace, strong naming etc., you can't do much with Visual Studio. However, for that you can use framework tools to generate RCW yourself.
AxImp.exe and TlbImp.exe are two such tools that ship with NET Framework SDK. In fact AxImp.exe alone is sufficient to generate required interops. We will how that works now. Suppose you have an ActiveX control called MyControl.OCX. Open the visual studio command prompt, change the directory to the folder where MyControl.ocx resides and run the below command.
 
AXIMP MyControl.OCX
 
This will generate two interops AxMyControl.dll and MyControl.dll. The default namespace in the prior one will be AxMyControl and default namespace in MyControl.dll will be MyControl. If you want to change the out putfile name to AxInterop.MyControl.dll, you can run the below command,

AXIMP MyControl.OCX /OUT:AxInterop.MyControl.dll
 
This will generate AxInterop.MyControl.dll and MyControl.dll. You can see that when using AXIMP tool, you do not have any control over other interop dll i.e. MyControl.dll. You also do not have control over default namespace name. So, if I want to give your own names say AxInterop.MyControl.dll and Interop.MyControl.dll with custom namespaces say LegacyControls, then I will do it as below:
First generate the interop assembly containign type definitions using TLBIMP tool as below,

 TLBIMP MyControl.OCX /OUT:Interop.MyControl.dll /namespace:LegacyControls
 
If you want the generated assembly to be strong named, you can supply the strong name key file to above command (as below)

TLBIMP MyControl.OCX ... /KEYFILE:MyCompanyKey.snk
 
Now generate the ActiveX interop using AXIMP tool using the above generated RCW,

AXIMP MyControl.OCX /OUT:AxInterop.MyControl.dll /RCW:Interop.MyControl.dll
 
and of course you can sign this assembly just like as explained before.
 
Now you have generated the two interops AxInterop.MyControl.dll and Interop.MyControl.dll with having namespace AxLegacyControls and LegacyControls respectively.
Note: You must register the OCX before you can use the generated interops.

15 June 2012

Interface Vs. Abstract Class, Why and When

Recently many people asked me this question - what is the difference between an abstract class and an interface? - This is a typical interview question and you can easily find answers like below in any .NET book.
  • abstract classes can contain pure abstract methods as well as concrete methods. But all methods in an interface are implicitly abstract
  • Methods in an abstract class can be protected, private, static etc. But, all items in an interface are implicitly public
  • A class can inherit multiple interfaces, but it can inherit only one abstract class.
  • etc. :)
But, in my view, one shouldn't compare interfaces and abstract classes because each of them have their own strength and weaknesses. I have also seen many people who go dumbfounded if someone asks them - Why do you use an interface? Or Why do you use an abstract class? I suggest you to go through this MSDN  page which gives you an idea of when to use what. In this blog, I will try to explore my knowledge on these two concepts.

Abstract Class
 
An abstract class is just another class with abstract keyword. But, the keyword 'abstract' adds some additional features to the class like - the class can contain just method declarations, an instance of the class cannot be created. So, below one is an abstract class.
 
public abstract class Animal
{
   public void Walk()
   {
      Console.WriteLine("Walking");
   }
   public void Sleep()
   {
      Console.WriteLine("Sleeping");
   }
   public abstract void Eat();
}
 
This class defines the basic characteristics of an animal like every animal sleeps, Moves, eats etc. But look at the Eat function. I have made it abstract in the sense - every animal can eat but what it eats depends upon the kind of animal.
 
class Cow : Animal
{
   public override void Eat()
   {
      Console.WriteLine("Eating grass");
   }
}
class Tiger : Animal
{
   public override void Eat()
   {
      Console.WriteLine("Eating meat");
   }
}
 
I hope above example doesn't need any explanation. You can see that abstract class defines an IS-A relationship. Which means Cow is an Animal, so Cow has all the basic characters of an Animal. e.g. Move and Sleep functions need not be re-defined in Cow class.

Also note that, If I add any new behaviour to base class, child classes need not be changed at all and they simply inherit the new behaviour. For example, if I define a new behaviour 'Drink' in animal class, both the child classes simply adapt the new behaviour immediately.

public abstract class Animal
{
   ...
   public void  Drink()
   {
       Console.WriteLine("Drinking water");
   }
   public abstract void Eat();
}
 
So, visioning is not a problem when you use abstract class. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface. Hence, If you want to create multiple versions of your component, create an abstract class.

One more thing to be noted that all these 2 classes Tiger, Cow are closely related i.e. both are Animals and share common behaviour of an animal. So, when the classes are closely related and share common functionality - Use Abstract classes. 

Interfaces 

In contrast to abstract class, an Interface defines a CAN-DO relationship rather than IS-A relationship. For example, the definition of String class looks like below,
 
class String : IComparable, ICloneable, IConvertible
..
 
This definition tells you that - you can compare string objects, you can clone string objects, you can convert string objects into other type.

Next thing is, when the classes are not closes related and you still want to have a common functionality among them - Use Interfaces. Let's consider an example,

 
public interface IEquatable<T>
{
   bool Equals(T other);
}
public class Person: IEquatable<Person>
{
   private string Name;
   private DateTime DateOfBirth;
   public bool Equals(Person other)
     {
      return other.Equals(other.Name) && other.DateOfBirth == this.DateOfBirth;
   }
}
public class Home : IEquatable<Home>
{
   private int HouseNumber;
   private int AreaCode;
   public bool Equals(Home other)
   {
       return other.AreaCode == this.AreaCode && other.HouseNumber == this.HouseNumber;
   }
}

 
Here 2 non-related classes Home and Person want to have Equality function. See that functionality 'Equals' is common between the 2 classes but the implementation is completely different. Hence, both Home & Person implement IEquatable interface but implement Equals method independently.

Now you can ask, if the implementations are different, what is the need of using interface? Of course, just remove the IEquatable interface and the program still works. So, why interface? Let me try to make it clear step by step.

Firstly, An interface acts as a CONTRACT. This means, any class that implements an interface agrees to implement all the methods in that interface. Also note that, (ideally) once implemented, interface (contract) definition cannot change i.e. you cannot add new methods and modify existing ones in an interface. This is very important aspect of interfaces. This assures the consumer of your class that, the class will implement all the methods defined in the interface contract though the implementation can change. For example, I know that Person class implements IEquatable interface. Hence I am guaranteed that Person class always contains Equals method. Hence, I am ensured that my below code always works.

IEquatable<Person> person1 = new Person();
IEquatable<Person> person2 = new Person();
bool areTheyEqual = person1.Equals(person2);

Having this, a new version of Person class is released and Equals method now includes a check for address of person also.
public class Person: IEquatable<Person>
{
   privatestring Name;
   private DateTime DateOfBirth;
   private Address Address;
   publicbool Equals(Person other)
     {
      return other.Equals(other.Name) &&
             other.DateOfBirth == this.DateOfBirth &&
             other.Address == this.Address;
   }
}

See that, though the implementation has changed, my consumer code  still works. So, having an interface implemented makes your class Backward compatible.

Secondly, interfaces are quite useful when you want call a method on dynamic object. For example, below helper function prints all the items in a collection - A List, Array, String etc.

public void DisplayAllItems<T>(IEnumerable<T> collection)
{
   foreach (var item in collection)
   {
       Console.WriteLine(item);
   }
}

In the above function, you can pass a List, array or any object that implements IEnumerable interface. Otherwise, we would need to implement the display logic for each collection type separately.

These are 2 examples of why to use interfaces. There are other lot of reasons for using interfaces like laying out complex architectures, implementing design patterns etc. But, I hope this blog gives you an idea of why to use interfaces.

That concludes the discussion of differentiating between interface & abstract class, which one to prefer & when. I hope you enjoyed reading my blog. Please put your feedback which help me in improving myself and also to help others.