Monthly Archives: March 2013

MarkupExtension

The MarkupExtension is the base class for things like StaticResource, DynamicResource, Binding and so on. It basically allows derived classes to participate in XAML more like a first class citizen.

For example, everyone and their dog has written a BooleanToVisibilityConverter (or those less prone to reinventing the wheel will have used something similar from one of the many WPF/XAML frameworks). But for the sake of this post let’s create one again.

public class BooleanToVisibilityConverter : IValueConverter
{
   public object Convert(object value, Type targetType, object parameter,
                         CultureInfo culture)
   {
      bool result = (value is bool?) ?
                         ((bool?) value).GetValueOrDefault(false) :
                         false;
      if(value is bool)
      {
         result = (bool) value;
      }
      return result ? Visibility.Visible : Visibility.Collapsed;
   }

   public object ConvertBack(object value, Type targetType, object parameter,
                             CultureInfo culture)
   {
      return (value is Visibility) ? (Visibility) value == Visibility.Visible : false;
   }
}

Now to use this in XAML we need to declare it within a ResourceDictionary

<Controls:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />

and to use we do the following

<Button Content="Cancel" Visibility="{Binding IsCancelVisible, 
    Converter={StaticResource BooleanToVisibilityConverter}}" />


There’s absolutely nothing wrong with this approach, but we could alter things slightly by deriving the BooleanToVisibilityConverter from MarkupExtension as per the following

public class BooleanToVisibilityConverter : MarkupExtension, IValueConverter
{
   public override object ProvideValue(IServiceProvider serviceProvider)
   {
      return this;
   }

   // previous code unaltered
}

Now we can remove the entry from the ResourceDictionary and alter the usage in the XAML for the button declaration to

<Button Content="Cancel" Visibility="{Binding IsCancelVisible, 
   Converter={Controls:BooleanToVisibilityConverter}}">


Well you may be thinking that all you gained was the removal of the ResourceDictionary line in the XAML, but actually we’ve now opened up the BooleanToVisibilityConverter to allow it to be more like built in XAML elements.

One thing you might find with alternate BooleanToVisisbilityConverters is that they either use Visibility.Collapsed or Visibility.Hidden for false. Obviously these two Visibility values differ (collapsed allows the parent layout to use the space where a component is collapsed, hidden means the component still takes up space in the layout but is now invisible).

So it’d be nice if out BooleanToVisibilityConverter could have false assigned to either Visibility.Collapsed or Visibility.Hidden depending upon our specific requirement.

So we can change our BooleanToVisibilityConverter source to

public class BooleanToVisibilityConverter : MarkupExtension, IValueConverter
{
   public BooleanToVisibilityConverter()
   {
      WhenFalse = Visibility.Collapsed;
   }

   public BooleanToVisibilityConverter(Visibility whenFalse)
   {
      WhenFalse = whenFalse;
   }

   [ConstructorArgument("WhenFalse")]
   public Visibility WhenFalse { get; set; }

   public override object ProvideValue(IServiceProvider serviceProvider)
   {
      return this;
   }

   public object Convert(object value, Type targetType, object parameter,
                         CultureInfo culture)
   {
      bool result = (value is bool?) ?
                        ((bool?) value).GetValueOrDefault(false) :
                        false;
      if(value is bool)
      {
         result = (bool) value;
      }
      return result ? Visibility.Visible : WhenFalse;
   }

   public object ConvertBack(object value, Type targetType, object parameter,
                             CultureInfo culture)
   {
      return (value is Visibility) ?
                (Visibility) value == Visibility.Visible : false;
   }
}

As you see we’ve now added a new property, WhenFalse, and defaulted this in the constructor and ofcourse altered the return in the Convert method to return WhenFalse when the boolean is false. The ConstructorArgumentAttribute and the non-default constructor are not actually required for this to work, but are here for serialization.

In XAML we now simply declare our button as

<Button Content="Cancel" Visibility="{Binding IsCancelVisible, 
    Converter={FolderViewer:BooleanToVisibilityConverter 
    WhenFalse=Collapsed}}">

Embedding code in your XAML

First off a disclaimer. Just because you can do this doesn’t mean you should :)

<x:Code>
   <![CDATA[
   private void OKButton_Click(object sender, RoutedEventArgs e)
   {
      MessageBox.Show("OK Clicked");
   }
   ]]>            
</x:Code>

<Button Content="OK" Width="80" Margin="3" Click="OKButton_Click" />

There’s not a lot to say about this one except that it’s possible to embed code in XAML. Obviously it’s easier to code it, generally speaking, in the code behind and better still in the view model. But the option is there :)

Investigating Autofac

Time to try some different IoC frameworks. Let’s take a look at the basics of Autofac. Using the simple IService implementation and a client with a constructor that requires the IService injected into we get the following code.

public interface IService
{
   void Run();
}

public class LocalService : IService
{
   public void Run()
   {
      Console.WriteLine("LocalService");
   }
}

public interface IClient
{
   IService Service { get; }

   void Run();
}

public class Client : IClient
{
   public Client(IService service)
   {
      Service = service;
   }

   public IService[] Service { get; private set; }

   public void Run()
   {
      Service.Run();
   }
}

We can set up bindings in code using the following

var builder = new ContainerBuilder();
builder.RegisterType().As();
builder.RegisterType().As();

var container = builder.Build();

var client = container.Resolve();
client.Run();

If we have multiple IService implementations then changing the Client to

public interface IClient
{
   IService[] Service { get; }

   void Run();
}

public class Client : IClient
{
   public Client(IService[] service)
   {
      Service = service;
   }

   public IService[] Service { get; private set; }

   public void Run()
   {
      foreach(IService service in Service)
         service.Run();
   }
}

var builder = new ContainerBuilder();
builder.RegisterType().As();
builder.RegisterType().As();
builder.RegisterType().As();

var container = builder.Build();

var client = container.Resolve();
client.Run();

Now let’s remove the constructor and use property injection. The client changes to

public class Client : IClient
{
   public IService[] Service { get; set; }

   // the run method as before
}

There’s no attributes or the likes to suggest that a property should be injected into. The change is in the binding code, just changing the Client registration code to

builder.RegisterType<Client>().As<IClient>().PropertiesAutowired();

Investigating Ninject

Whilst I’ve used IoC frameworks such as Unity, MEF, Spring.net etc. in the past, I’ve not gotten around to playing with Ninject. So time to have a play.

First off I created a simple interface, IService and corresponding implementing LocalService

public interface IService
{
   void Run();
}

public class LocalService : IService
{
   public void Run()
   {
      Console.WriteLine("Local Service");
   }
}

Now I created a simple client object

public interface IClient
{
   IService Service { get; }

   void Run();
}

public class Client : IClient
{
   public Client(IService service)
   {
      Service = service;
   }

   public IService Service { get; private set; }

   public void Run()
   {
      Service.Run();
   }
}

So as you can see the idea is simple. A client requires an IService passed by the IoC into the constructor. At some point we’ll call the client’s Run method and expect a LocalService to run. Obviously error handling etc. omitted for brevity.

Now let’s create the configuration/bindings to allow Ninject to inject the required service into the client.

var kernel = new StandardKernel();

kernel.Bind<IService>().To<LocalService>();
kernel.Bind<IClient>().To<Client>();

var client = kernel.Get<IClient>();
client.Run();

What about if we have multiple IService implementations, see the changes below which include the client accepting an array of IService and the kernel code includes an additional binding.

public class RemoteService : IService
{
   public void Run()
   {
     Console.WriteLine("RemoteService");
   }
}

public interface IClient
{
   IService[] Service { get; }

   void Run();
}

public class Client : IClient
{
   public Client(IService[] service)
   {
      Service = service;
   }

   public IService[] Service { get; private set; }

   public void Run()
   {
      foreach(IService service in Service)
         service.Run();
   }
}

var kernel = new StandardKernel();

kernel.Bind<IService>().To<LocalService>();
kernel.Bind<IService>().To<RemoteService>();
kernel.Bind<IClient>().To<Client>();

var client = kernel.Get<IClient>();
client.Run();

So using Ninject to inject into a constructor is simple. Now let’s make a change to the client constructor by removing the parameter and instead use property injection.

public class Client : IClient
{
   [Inject]
   public IService[] Service { get; set; }

  // the Run method remains unchanged as does the binding code
}

Investigating Memory – Strings

A while back I had to investigate why our application seemed to be using a large amount of memory in certain usage patterns. What we would find is that several calls to a web service would cause an OutOfMemoryException on the client.

Note: The underlying problem was the good old, “references not being released” to an object and thus garbage collection not taking place. But more interesting at the time was the information I found from the steps below.

To investigate the memory usage I loaded up WinDbg and attached (F6) to the instance of the application I wanted to investigate. Then carried out the following steps.

  • I typed .load sosex into the WinDbg command line (see http://stevestechspot.com)
  • I typed !dumpheap -stat into the WinDbg command line to view the memory

At the end of the heap dump I noticed the type consuming the largest amount of memory (by quite a long way) was the humble System.String. This tweaked my interest and so I dug deeper using WinDbg.

  • I typed !dumpheap -strings into WinDbg

This took a while to complete (due to the size of the application) but I noticed that when the dump was completed there were a large number of strings which seemed to have a very large number of instances duplicates stored in memory. Amounting to a hefty amount of the memory being used for the same string stored thousands of times.

Note: The problem with !dumpheap -strings is that it does not output the object reference because it’s outputting a summary of each string’s usage, but from this we can see the strings that take the most memory and/or most instances of and the use the sosex command !strings to inspect each instance in more detail. Type !help !strings to view help for the command. One useful option is !strings /m:

What was happening was that large amounts of data were being retrieved from our web services and in that data was a massive number of duplicate strings. Unfortunately I could do nothing with the web service itself, but I could attempt to address the strings in the client application.

As you may know there’s a static method on the String class called Intern. In essence this acts as an application wide string cache (or more precisely an AppDomain cache), calling it like this

o.Name = String.Intern(o.Name);

Will in essence replace the o.Name string which a reference to the one stored in the application cache, thus the previous o.Name string can be garbaged collected as it’s no longer referenced.

This reduced the amount of duplicates and memory immediately, however there’s an obvious problem with the String.Intern and that is it’s an AppDomain cache. This means that as we read strings from our webservices these add to the cache and never get garbage collected, slowly added more and more unique strings to the cache. This is fine for const strings which are automatically interen’d but not so good for an application mean’t to run pretty much 24/7.

I initially looked to implement my own Dictionary based cache but almost everything has been done by somebody else on the web, so after a short search I came across the StringReference class which did exactly what I wanted. It allows us to use the good bits from Intern but with the ability to clean up unused strings over time.

A simple WPF TriggerAction to turn events into commands

This is nothing new. I know of several MVVM frameworks that do this, but this was my take on a solution for the following:

So you have events on a UIElement, for example a Button has MouseEnter and MouseLeave (amongst others). By default the events require an event handler which would might be placed in the “code behind” in the view itself. But this is no use if, for example a MouseEnter should update some data from the view model unless you want to do more coding in the view to access the view model and makes calls directly on it, which is a somewhat against the spirit of MVVM. So what would be cool is if the MouseEnter could instead be bound to a view model command instead.

Being that part of the mechanism already exists in EventTriggers then we just need to supply a trigger action to bind to the view model.

For example the XAML might look like:

<Button Content="Cancel" Width="80" Margin="3" >
   <i:Interaction.Triggers>
      <i:EventTrigger EventName="MouseEnter">
         <controls:CommandAction Command="{Binding ClearSearch}" />
      </i:EventTrigger>
   </i:Interaction.Triggers>
</Button>

The code for the TriggerAction is simple

public class CommandAction : TriggerAction<DependencyObject>
{
   public static readonly DependencyProperty CommandProperty =
	DependencyProperty.Register("Command", typeof(ICommand), typeof(CommandAction),
	new PropertyMetadata(null, OnCommandChanged));

   public static readonly DependencyProperty CommandParameterProperty =
	DependencyProperty.Register("CommandParameter", typeof(object), typeof(CommandAction),
	new PropertyMetadata(null, OnCommandParameterChanged));

   private IDisposable canExecuteChanged;

   public ICommand Command
   {
      get { return (ICommand)GetValue(CommandProperty); }
      set { SetValue(CommandProperty, value); }
   }

   public object CommandParameter
   {
      get { return GetValue(CommandParameterProperty); }
      set { SetValue(CommandParameterProperty, value); }
   }

   private static void OnCommandChanged(DependencyObject sender, 
                   DependencyPropertyChangedEventArgs e)
   {
      CommandAction ev = sender as CommandAction;
      if(ev != null)
      {
         if (ev.canExecuteChanged != null)
	 {
	    ev.canExecuteChanged.Dispose();
	 }

	 ICommand command = e.NewValue as ICommand;
	 if (command != null)
	 {
	    ev.canExecuteChanged = Observable.FromEventPattern(
			x => command.CanExecuteChanged += x,
			x => command.CanExecuteChanged -= x).Subscribe
			(_ => ev.SynchronizeElementState());
	 }
      }
   }

   private static void OnCommandParameterChanged(DependencyObject sender,
            DependencyPropertyChangedEventArgs e)
   {
      CommandAction ev = sender as CommandAction;
      if (ev != null)
      {
         ev.SynchronizeElementState();
      }
   }

   private void SynchronizeElementState()
   {
      ICommand command = Command;
      if (command != null)
      {
         FrameworkElement associatedObject = AssociatedObject as FrameworkElement;
	 if (associatedObject != null)
	 {
	    associatedObject.IsEnabled = command.CanExecute(CommandParameter);
	 }
      }	
   }

   protected override void Invoke(object parameter)
   {
      ICommand command = Command;
      if(command != null)
      {
         command.Execute(CommandParameter);
      }
   }
}

We derive our class from TriggerAction and declare any dependency properties etc. we want on it. So if you ignore all the setting up of Command & CommandParameter code, this really boils down to the override of the Invoke method. This is what’s called when the trigger condition is met.

Blend Behaviors in WPF

A quick post about blend behaviors in WPF. A behavior (from the System.Windows.Interactive assembly) allows us to add functionality to elements within the UI tree. An example might better serve to describe what one is and how to write one.

Let’s make things simple and say we have a UI element which we want to fade into the background when not focus. So we can create a class derived from Behavior<>. Looking at the properties on a UIElement this will suffice for our needs so we’ll derive our FadeOnLostFocusBehavior (bit of a mouthful) from Behavior.

If we jump straight to the code we get something like

public class FadeOnLoseFocusBehavior : Behavior<UIElement>
{
   private const float FADED = 0.2f;

   protected override void OnAttached()
   {
      AssociatedObject.LostFocus += AssociatedObject_LostFocus;
      AssociatedObject.GotFocus += AssociatedObject_GotFocus;

      // this just ensures a default state of faded for the control
      AssociatedObject.Opacity = FADED;

      base.OnAttached();
   }

   protected override void OnDetaching()
   {
      AssociatedObject.LostFocus -= AssociatedObject_LostFocus;
      AssociatedObject.GotFocus -= AssociatedObject_GotFocus;

      base.OnDetaching();
   }

   private void AssociatedObject_LostFocus(object sender, RoutedEventArgs e)
   {
      AssociatedObject.Opacity = FADED;
   }	

   private void AssociatedObject_GotFocus(object sender, RoutedEventArgs e)
   {
      AssociatedObject.Opacity = 1;
   }
}

The above is very simple. When we attach the behavior to the UIElement we connect to the required events on the AssociatedObject. When we detach from the UIElement we detach from the events on the AssociatedObject. The rest is self-explanatory.

The XAML for this example would look like

<Button Content="Cancel" Width="80" Margin="3" >
   <i:Interaction.Behaviors>
      <controls:FadeOnLoseFocusBehavior />
   </i:Interaction.Behaviors>
</Button>

_ in C#

This is a quirky post. Something I’ve been using for a while is the _ in situations where I’ve an anonymous delegate with one argument where I don’t care about the argument, for example

ThreadPool.QueueUserWorkItem(_ => DoSomething());

But never thought of using it as a class name or variable name (not sure why I hadn’t thought of it apart from it seeming like a mad thing to do :)), for example

class _
{
   // members
}

public void Main()
{
   _ _ = new _();
}

Note: I’m not saying this is a good thing to use, just that it’s possible

Reactive Extensions Tips & Tricks

Creating an observable from an event

Observing a generic event such as the StatusChangedEvent (EventHandler<StatusChangedEvent>) is as simple as

var statusChanged = Observable.FromEventPattern<StatusChangedEventArgs>(
                e => KinectSensor.KinectSensors.StatusChanged += e,
                e => KinectSensor.KinectSensors.StatusChanged -= e);

Cast and OfType

Cast and OfType allow us to observe an observable and in the case of Cast will cast each item to the specified type, causing on OnError if the type cannot be cast (due to an InvalidCastException). OfType does much the same except when a type is not castable to the specified type it’s ignored.

Cast in use…

// cast in use, failing due to InvalidCastException
object[] items = new object[3];
items[0] = 23;
items[1] = "Hello";
items[2] = 444;

var o = items.ToObservable().Cast<int>().Subscribe(Console.WriteLine);

The result of the above will be 23, then an error.

OfType in use…

// OfType used, only int's will be output
object[] items = new object[3];
items[0] = 23;
items[1] = "Hello";
items[2] = 444;

var o = items.ToObservable().OfType<int>().Subscribe(Console.WriteLine);

The result of this will be 23 & 44, with the string ignored.

Unit testing a ReactiveUI ViewModel

This is a quick post about unit testing a view model that uses ReactiveUI. More specifically it’s about testing the MessageBus code within the view model.

So the scenario is simple. I have a view model (of type ConfigurationViewModel) when anything in the application wishes to delete configuration data it sends the appropriate message onto the ReactiveUI MessageBus and the idea is that the configuration view model then correctly calls the delete method on its underlying configuration class. I’m using RhinoMocks to mock the underlying configuration class in the test below.

[Test]
public void DeleteConfiguration_ShouldCallUnderlyingObjectToDeleteProject()
{
   using (mocks.Record())
   {
      Expect.Call(() => configuration.Delete("MyProject"));
   }

   using (mocks.Playback())
   {
      MessageBus.Current.SendMessage(new ProjectViewModel("MyProject", false, false), "Delete");
   }
}

Now this worked perfectly so I happily moved onto another similar test for another part of the configuration. I ran up the tests after implementing the code and one of the tests failed. I ran the single test again now moving from ReSharper’s test runner to NUnit’s. The test passed. I ran all tests and again it failed.

After some reading/searching around I found a post on StackOverflow where Paul Betts mentions the RxApp.DeferredScheduler is exactly that, deferred. After a bit of testing I realised then that I needed to switch this to an ImmediateScheduler to resolve the issues. Once I did this everything worked perfectly.

So the note to myself is to add the code

[SetUp]
public void SetUp()
{
   RsApp.DeferredScheduler = Scheduler.Immediate;

   // setup the mocks etc.
}

A small postscript to the above is that after reading the ReactiveUI code on GITHUB I realised that it attempts to automatically switch the DeferredSchduler to Immediate if it detects it’s being run from a test runner. I removed the above code (in the SetUp) and indeed it all worked fine now. So I’m note quite sure what caused the problem previously, but at least I learned how to solve it if it occurs again.