March 26, 2012

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);
    }
}

February 21, 2012

Asynchronous Programming with Async/Await

Easier Asynchronous Programming with the New Visual Studio Async

Every time an await is encountered, the currently executing method signs up the rest of the method as the thing to do when the current task is complete, and then immediately returns. Somehow each task will complete itself—either by being scheduled to run as an event on the current thread, or because it used an I/O completion thread or worker thread—and will then cause its continuation to “pick up where it left off” in executing the rest of the method.

Async Programming in Visual Studio 2010

The thing doing that work may be a background thread, an I/O completion thread, a graphic processing unit, or even the current thread. It doesn’t matter to the caller.

Await signifies two related things. First, it says that everything remaining in the method becomes the continuation for the method. A ‘continuation’ represents where the method will continue once the expression being awaited completes its work. Secondly, it tells the method to return.


Pause and Play with Await - How the Await and Async work underneath the covesr and how you can prepare for the m in .NET 4.0.

What is Binding?

Taken from the following article
What is "binding" and What makes it late? by Eric Lippert
Binding is the association of a syntactic element that names a method with a logical element of the program. So, speaking generally I would say that "binding" is any association of some fragment of syntax with some logical program element.

Basically by "early binding" we mean "the binding analysis is performed by the compiler and baked in to the generated program"; By "late binding" we mean "some aspect of the binding will be performed by the runtime" and therefore a binding failure will manifest as a runtime failure.

Early and late binding might better be called "static binding" and "dynamic binding"; static binding is binding performed using "static" facts known to the compiler, and dynamic binding is performed using facts "dynamically" known to the runtime.

February 17, 2012

WPF/Silverlight Data Binding

WPF Basic Data Binding FAQ - Better explanation than the one below.

WPF Data binding cheat sheet

Data Binding Overview - Basically, the target is the control and the source is the code property. Typically, each binding has these four components: a binding target object, a target property, a binding source, and a path to the value in the binding source to use. For example, if you want to bind the content of a TextBox to the Name property of an Employee object, your target object is the TextBox, the target property is the Text property, the value to use is Name, and the source object is the Employee object.

http://msdn.microsoft.com/en-gb/magazine/cc163299.aspx - Data Binding in WPF. Good introduction. Good short description of Xml data binding (though not 2 way I notice)

http://msdn.microsoft.com/en-us/magazine/cc700358.aspx - Customize Data Display with Data Binding and WPF. Some good stuff on hierarchical data templates and how to use them to fill a tree view using object data binding.

http://www.codeproject.com/Articles/26270/Understanding-WPF-via-ASP-NET - Nice article comparing WPF and ASP.NET data binding etc.

Also look at these related blogs
DisplayMemberpath
Data Templates

Bind "IsEnabled" of one control "cbXXX" to "IsChecked" property of another with name "cbYYY" in Xaml:
... Name="cbXXX" IsEnabled="{Binding ElementName=cbYYY, Path=IsChecked}" ...

February 16, 2012

DisplayMemberPath

DisplayMemberPath - Allows for simple binding on list type controls. Name or path on bound object that will be displayed for each item in the control.

See this article http://johnpapa.net/binding-to-silverlight-combobox-and-using-selectedvalue-selectedvaluepath-and-displaymemberpath - Nice ComboBox example that allows the user to chose some colors.