March 28, 2012

WPF/Silverlight MVVM

Quick Intro to MVVM A small introduction

Getting Started with the MVVM Pattern in Silverlight Applications

MVVM Light Toolkit
Download it here - There is a couple of videos here as well!

Chapter 5: Implementing the MVVM Pattern
Chapter 6: Advanced MVVM Scenarios - Most introductions only explain the topic in a basic way which does not occur in reality. Here, they show how to deal with the tricksey areas

Simplifying commands in MVVM and WPF - I like the adapted approach proffered by David N. in the comments

Using the BackgroundWorker in a Silverlight MVVM Application - Most of my apps have background worker threads or threading in some manner.

WPF MVVM Commands - new reduced-boilerplate recipe - Not so keen on this approach

March 26, 2012

Custom commands with standard menus

Define the command:
public static class CustomCommands
{
    private static RoutedCommand exitCommand;

    static CustomCommands()
    {
        exitCommand = new RoutedCommand("ExitApplication", typeof(CustomCommands));
    }

    public static RoutedCommand Exit
    {
        get
        {
            return (exitCommand);
        }
    }

}
Define the command in the window bindings:
<Window.CommandBindings>
        <CommandBinding
          Command="{x:Static local:CustomCommands.Exit}"
    Executed="Exit_Execute" 
          CanExecute="Exit_CanExecute" />
    </Window.CommandBindings>
Of course you'll have to define the namespace in the window/page class node:
<Window ...
xmlns:local="clr-namespace:MyNamespace"
... >
Alternatively, define the command in the window constructor:
InitializeComponent();
...
   CommandBindings.Add(
    new CommandBinding(
   CustomCommands.Exit, // this is the command object
   Exit_Execute,      // execute
   Exit_CanExecute));// can it execute?
Define the menu item that will call the command
<MenuItem Header="E_xit" Command="local:CustomCommands.Exit" />
Now define the event handlers that will execute the command
private void Exit_Execute(object sender, ExecutedRoutedEventArgs e)
{
    this.Close();
}

private void Exit_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = CanExitApplication();
    e.Handled = true;
}

Using Application Commands

Define the command binding
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.Close"
 Executed="CloseCommandHandler"
 CanExecute="Close_CanExecute"
 /> 
 ...
 </Window.CommandBindings> 
and then define the menu item:
<MenuItem Header="E_xit" Command="ApplicationCommands.Close" />
Again ensure that within the code behind window class that the event handlers are defined:
private void Close_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = true;
    e.Handled = true;
}

private void Close_Execute(object sender, ExecutedRoutedEventArgs e)
{
    DoClose();
}
Beware of using commands with Context Menus. There is a 'gotcha' here. This is explained here: How to Solve Execution Problems of RoutedCommands in a WPF ContextMenu The simplest solution is to call 'Focus()' on the parent window.

March 6, 2012

Implementing ==, != Operators In Reference Types

For more on equality operators see the Equals Operator Pattern

Microsoft guideline: Guidelines for Overloading Equals() and Operator == (C# Programming Guide)

Find out about The ReferenceEquals() method - Standard class operator == does reference comparison, so it will end up returning false if the two arguments point to different references where both refences hold the same state. To define == operator for a reference type you must be careful to define it in terms of "RefenceEqual()" and "Equals()". If you use == within the definition you will likely get an infinite recursion. This blogs explains why. Value types do not have the same problem as "==" does not do a reference comparison, it compares the value types field by field for equality.

Following example shows how a reference object behaves when the '==' and '!=' operators are overriden and when they are not. The class 'With' has the operators overriden and the class 'Sans' has not.
class TestRefernceTypeEqualityOperator
{
  internal class With
  {
    public string Name { get; set; }
    public int UniqueId { get; set; }

    public override bool Equals(object obj)
    {
      if (obj == null)
        return false;

      if (object.ReferenceEquals(this, obj))
        return true;

      if (!(obj is With))
        return false;
      With selection2 = (With)obj;

      if ((this.UniqueId == selection2.UniqueId) &&
        (this.Name == selection2.Name))
        return true;

      return base.Equals(obj);
    }


    public static bool operator ==(With obj1, With obj2)
    {
      // IF obj1 1 is null
      //   so obj2 must be for equality
      // ELSE obj1 is not null,  
      //   compare it with obj2 using above Equals() operator
      if (ReferenceEquals(obj1, null))    
        return ReferenceEquals(obj2, null); 
      else                  
        return obj1.Equals(obj2);
    }

    public static bool operator !=(With obj1, With obj2)
    {
      return !(obj1 == obj2);
    }


    public override int GetHashCode()
    {
      string ensemble = this.UniqueId.ToString() + this.Name;
      return ensemble.GetHashCode();
    }

  }


  internal class Sans
  {
    public string Name { get; set; }
    public int UniqueId { get; set; }

    public override bool Equals(object obj)
    {
      if (obj == null)
        return false;

      if (object.ReferenceEquals(this, obj))
        return true;

      if (!(obj is Sans))
        return false;
      Sans selection2 = (Sans)obj;

      if ((this.UniqueId == selection2.UniqueId) &&
        (this.Name == selection2.Name))
        return true;

      return base.Equals(obj);
    }


    public override int GetHashCode()
    {
      string ensemble = this.UniqueId.ToString() + this.Name;
      return ensemble.GetHashCode();
    }


  }

  public void Test()
  {
    // Note that 'with' and 'with2' are different references 
    // with the same state
    With with = new With() { Name= "Smeg", UniqueId = 2739 };
    With with2 = new With() { Name = "Smeg", UniqueId = 2739 };
    With with3 = new With() { Name = "Smeg", UniqueId = 2740 };
    Trace.Assert(with.Equals(with2));
    Trace.Assert(with == with2);
    Trace.Assert(!(with != with2));
    Trace.Assert(!(with == null));
    Trace.Assert(!(null == with));

    Trace.Assert(!with.Equals(with3));
    Trace.Assert(with != with3);     
    Trace.Assert(!with2.Equals(with3));
    Trace.Assert(with2 != with3);

    // Note that 'sans' and 'sans2' are different references 
    // with the same state
    Sans sans = new Sans() { Name = "Smeg", UniqueId = 2739 };
    Sans sans2 = new Sans() { Name = "Smeg", UniqueId = 2739 };
    Sans sans3 = new Sans() { Name = "Smeg", UniqueId = 2740 };
    Trace.Assert(sans.Equals(sans2));
    Trace.Assert(!(sans == sans2));
    Trace.Assert(sans != sans2);
    Trace.Assert(!(sans == null));
    Trace.Assert(!(null == sans));

    Trace.Assert(!sans.Equals(sans3));
    Trace.Assert(sans != sans3);
    Trace.Assert(!sans2.Equals(sans3));
    Trace.Assert(sans2 != sans3);
  }
}
The 2 highlited lines show the difference. Without '==', '!=' operator the comparison is by reference so where 'with == with2' succeeds 'sans == sans2' fails even though the different references refer to objects with exactly the same state (and even though the 'Equals()' method does return true in this case).

March 1, 2012

Simple Generic ServiceLocator example

Find the root of all evil behind this pattern by Martin Fowler
What's the difference between the Dependency Injection and Service Locator patterns?

Here is a simple GenericServiceLocator class:
public class GenericServiceLocator
{
    #region Fast Thread Safe Singleton Implementation
        
    static GenericServiceLocator()
    {}

    private GenericServiceLocator()
    {}

    private static readonly GenericServiceLocator instance = 
        new GenericServiceLocator();

    public static GenericServiceLocator Instance
    {
        get
        {
            return instance;
        }
    }

    #endregion Fast Thread Safe Singleton Implementation

    Dictionary<object, object> interfaceToServiceMap = 
        new Dictionary<object, object>();

    public void AddService<IInterface>(IInterface svcImpl)            
    {
        Trace.Assert(typeof(IInterface).IsInterface);
        Trace.Assert(svcImpl != null);
        Trace.Assert(svcImpl is IInterface);
        Trace.Assert(!this.interfaceToServiceMap.
                               ContainsKey(typeof(IInterface)));
        this.interfaceToServiceMap[typeof(IInterface)] = svcImpl;
    }


    public IInterface GetService<IInterface>() 
    {
        Trace.Assert(typeof(IInterface).IsInterface);
        

        object obj = this.interfaceToServiceMap[typeof(IInterface)];
        return (IInterface)obj;
    }


    public bool HasService<IInterface>()
    {
        Trace.Assert(typeof(IInterface).IsInterface);

        return this.interfaceToServiceMap.
                                   ContainsKey(typeof(IInterface));
    }
}
Here is a simple tester for it:
class TestServiceLocator
{
    public interface IMyPieInterface
    {
        double GetPie();
    }

    public class PieMaker : IMyPieInterface
    {
        #region IMyPieInterface Members

        public double GetPie()
        {
            return Math.PI;
        }

        #endregion
    }

    public void Test()
    {
        GenericServiceLocator.Instance.
                          AddService<IMyPieInterface>(new PieMaker());
        Trace.Assert(GenericServiceLocator.Instance.
                          HasService<IMyPieInterface>());

        IMyPieInterface myPieMaker = GenericServiceLocator.Instance.
                          GetService<IMyPieInterface>();
        double pie = myPieMaker.GetPie();
        Trace.Assert(Math.Abs(Math.PI - pie) < 0.001);
    }
}