Category Archives: Programming

.NET CLR Version Tool

I’d not come across this tool before, but whilst checking the location of the sn.exe tool I spotted it and thought I’d see what it did.

So the clrver.exe can be run from the Visual Studio command prompt or found at a location where your SDK exists, for example

"%ProgramFiles%\\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\clrver.exe"

Just running clrver.exe without any arguments will tell you which versions of the CLR are installed on your machine, whilst using the switch -all will result in a list of applications/processes running using the .NET CLR and tells us the version they’re using. If you already know the process id (pid) you can use clrver 123 to list the .NET CLR version being used by pid 123.

Observable.FromEventPattern discussed

I was actually looking through my past blog posts and noticed I’ve never published anything on Reactive Extensions (Rx). I actually have a draft “beginners” guide which I started a couple of years back, but never completed, so I may end up publishing that at a later date.

Note: The best resource for Rx information that I’ve found is Introduction to Rx, I’d definitely recommend you visit that site for complete and excellent documentation on Rx.

Okay, for this post I’m just going to focus on the FromEventPattern. Even though the syntax is pretty simple I have a habit of forgetting it everytime I come to use it, so as this blog is about refreshing my memory, I thought I’d write a blog post dedicated to this method.

Why use Rx instead of handling events in the conventional way?

One of the most obvious reasons to use Rx to handle events is that it can help stop those pesky memory leaks when we forget to unsubscribe to an event. Another reason is the IObservable returned from FromEventPattern is composable and we can filter events that we’re not interested in and/or marshal events from one thread onto another – for example when events are coming from a worker thread we might marshal them onto the UI thread.

Take a look at Observable.FromEventPattern Method to see the current syntax/overloads for this method.

I will not be covering all the overloads here but will instead look at the three I’ve used the most. So let’s get started…

FromEventPattern with an EventHandler which takes no EventArgs

In some cases you might have an event handler which doesn’t use EventArgs, for example

public event EventHandler Reverted;

in such a case we use the overload

public static IObservable<EventPattern<EventArgs>> FromEventPattern(
	Action<EventHandler> addHandler,
	Action<EventHandler> removeHandler)

So our code might look like this

var o = Observable.FromEventPattern(
   x => domainObject.Changed += x,
   x => domainObject.Changed -= x).
   Subscribe(_ => DoSomething());

FromEventPattern with standard event patterns (using the EventHandler class)

Building on the previous syntax…

In many cases, where the events that we want to subscribe to, use the “standard .NET event pattern”, (for example where the handler takes an EventArgs derived class) and were declared using the syntax

public event EventHandler<CellsInViewChangedEventArgs> CellsInViewChanged;

we will use this overload. Note: This version expects an EventHandler<> object.

public static IObservable<EventPattern<TEventArgs>> FromEventPattern<TEventArgs>(
	Action<EventHandler<TEventArgs>> addHandler,
	Action<EventHandler<TEventArgs>> removeHandler
)
where TEventArgs : EventArgs

To use this we simple supply the EventArgs derived type, for example

var o = Observable.FromEventPattern<CellsInViewChangedEventArgs>(
   x => grid.CellsInViewChanged += x,
   x => grid.CellsInViewChanged -= x).
   Subscribe(_ => DoSomething());

FromEvent pattern with standard event patterns (not using the Event Handler class)

Finally, for this post, in some cases we have events which do not use the EventHandler<> class, for example the WPF RoutedEvents use

public delegate void RoutedEventHandler(
   object sender, 
   System.Windows.RoutedEventArgs e)

In such cases we need to supply both the Delegate type and EventArgs type to the FromEventPattern, hence we use the syntax

public static IObservable<EventPattern<TEventArgs>> FromEventPattern<TDelegate, TEventArgs>(
	Action<TDelegate> addHandler,
	Action<TDelegate> removeHandler
)
where TEventArgs : EventArgs

our code will now look like this

var o = Observable.FromEventPattern<RoutedEventHandler, RoutedEventArgs>(
   x => button.Click += x,
   x => button.Click -= x).
   Subscribe(_ => DoSomething());

More…

I don’t intend to cover all the possible uses of the IObservable which is returned by the FromEventPattern, but suffice to say (as mentioned earlier). We can ensure events are marshaled onto the thread which created the observable, so for example if we create this from the UI thread we can write

var o = Observable.FromEventPattern<ValuesChangedEventArgs>(
   x => server.ValuesChanged += x,
   x => server.ValuesChanged -= x).
   ObserveOn(SynchronizationContext.Current).
   Subscribe(_ => DoSomething());

here, the ObserveOn will ensure that the events that might be coming from a worker thread are marshaled onto the current thread. Obviously if this was created on the UI thread this will marshal back onto that thread.

Creating awaitable types

If you’ve used async/await in your applications, you’ll generally await a Task, but you can actually make your own type awaitable. Let’s look at how we’d do this.

Why are Task’s awaitable?

A Task is awaitable, not because it’s a Task type, but its because it supports a specific method name which returns a TaskAwaiter or TaskAwaiter for the Task type. So let’s take a look at what this method looks like

public TaskAwaiter GetAwaiter()

So it’s really that simple, if we want to make our object awaitable we simply define the same method in our type.

What is a TaskAwaiter?

A TaskAwaiter is a struct which implements the ICriticalNotifyCompletion interface and the INotifyCompletion interface (the ICriticalNotifyCompletion derives from the INotifyCompletion). But this still wouldn’t make the TaskAwaiter awaitable it also needs the property IsCompleted and the method GetResult – more on this in “the rules for an “Awaiter” type” below.

It does seem strange that these methods weren’t all put into a single interface, but there you have it.

How do I create a bare minimum awaitable type?

Let’s first review the rules for making our type awaitable

  • Our type should have a method named GetAwaiter which takes no arguments and returns a suitable “Awaiter” type

and now the rules for an “Awaiter” type

  • The type should implement the INotifyCompletion interface or the ICriticalNotifyCompletion interface
  • It should have a IsCompleted property of type boolean
  • It should have a GetResult method which returns void or a result value
    • and now let’s put this together into a somewhat pointless type which demonstrates a bare minimum set of requirements to get this type to be awaitable

      public class MyObject
      {
         public MyAwaiter GetAwaiter()
         {
            return new MyAwaiter();
         }
      }
      
      public struct MyAwaiter
      {
         public void OnCompleted(Action continuation)
         {
            continuation();
         }
      
         public bool IsCompleted { get; private set; }
      
         public void GetResult()
         {			
         }
      }
      

      and now in use, we would have something like this

      var o = new MyObject();
      await o;
      

      Note: if you do not call the conitnuation() action in the OnCompleted method the code will block indefinitely.

      The flow of this code goes as follows…

      await o is called, this calls GetAwaiter on MyObject which returns a MyAwaiter. Next IsCompleted is checked, if the awaiter has already completed then control returns to the line after the await, if it’s false OnCompleted is called which basically blocks until the continuation is called, finally the GetResult method is called.

      Extension methods that are awaitable

      So we’ve discussed creating our own type, making it awaitable and even creating an awaiter type, but another approach which one might use is creating extension methods and instead of going to the hassle of creating an awaiter type, we’ll simply reuse the TaskCompletionSource type which can be used as a puppet task.

      Let’s go straight to some code which I’ve unashamedly lifted from Stephen Toub’s blog post await anything.

      public static TaskAwaiter<int> GetAwaiter(this Process process)
      {
         var tcs = new TaskCompletionSource<int>();
         process.EnableRaisingEvents = true;
         process.Exited += (s, e) => tcs.TrySetResult(process.ExitCode);
         if (process.HasExited)
         {
            tcs.TrySetResult(process.ExitCode);
         }
         return tcs.Task.GetAwaiter();
      }
      

      and we would use this as follows

      await Process.Start(“notepad.exe”)
      

      Looking at the extension method you can see we’re going to use the TaskCompletion classes GetAwaiter to return the awaiter type (in this case a TaskAwaiter) and we simply try to set the result on the TaskCompletionSource if, or when, the process exits.

      References

      await anything
      Design change: new “await” pattern for greater efficiency

Implementing a storyboard in code

So, I have a requirement to flash a cell (or row) in a XamDataGrid when an error occurs on the underlying model for the cell/row. I’m currently implementing this in code simply because I’ve inherited a new control from the XamDataGrid to handle all my requirements.

I won’t go into the full implementation of the style, but suffice to say the bit that matters looks like this

var style = new Style(typeof (CellValuePresenter));

var trigger = new DataTrigger
{
   Binding = new Binding("DataItem.IsValid"),
   Value = false
};

var animation = new BrushAnimation
{
   From = Brushes.LightPink,
   To = Brushes.Firebrick,
   Duration = TimeSpan.FromSeconds(0.2),
   AutoReverse = true
};

var storyboard = new Storyboard
{
   RepeatBehavior = RepeatBehavior.Forever
};

Storyboard.SetTargetProperty(animation, 
   new PropertyPath(BackgroundProperty));
storyboard.Children.Add(animation);

var enterBeginStoryboard = new BeginStoryboard
{
   Name = "flashingStoryboard",
   Storyboard = storyboard 
};

style.RegisterName("flashingStoryboard", enterBeginStoryboard);

trigger.EnterActions.Add(enterBeginStoryboard);
trigger.ExitActions.Add(
   new StopStoryboard 
   { 
      BeginStoryboardName = "flashingStoryboard" 
   });

style.Triggers.Add(trigger);

In the above code we obviously create the style, with the target type of the CellValuePresenter. Then we’re using a trigger to detect when the view model’s IsValid property is false. This will cause our flashing animation/storyboard to pulse the background brush from light pink to firebrick and back.

Note: The BrushAnimation object is taken from a stackoverflow post Brush to Brush Animation

The creation of the animation and storyboard, hopefully, are fairly self-explanatory. The idea is that when the trigger EnterActions is called the animation begins and when the ExitAction occurs the storyboard is stoppped. We need to supply a name to the StopStoryboard object and here’s where my first mistake was made.

The line style.RegisterName(“flashingStoryboard”, enterBeginStoryboard); is important. Without it we will find that the named storyboard is not found by the StopStoryboard object. The storyboard needs to have the name registered within the
style’s namescope otherwise you’ll get the error I encountered which is an InvalidOperation exception

‘flashingStoryboard’ name cannot be found in the name scope of ‘System.Windows.Style’

This exception will only occur when the StopStoryboard code is called as this is the point it needs to find the object from the namescope.

F# MVVM plumbing code

I’m trying to see how far I can go in implementing a WPF application purely in F# (and I don’t mean that third party or framework libraries must be F#, just my code). The application isn’t going to be massive or probably very complex, I’m just interested in finding the “pain points” of using F# and WPF.

In previous posts I’ve created the code to start-up an application and load the main window along with how I might assign a view model to the DataContext of the main window.

I now want to take care of the usual mundane tasks such as binding to a view model, handling property change events on the INotifyPropertyChanged interface and implementing commands using the ICommand interface.

Handling property changes and INotifyPropertyChanged

In my C# WPF projects I use a extension methods that both assign values (if a property has changed) and raises PropertyChanged events using Expression objects as opposed to “magic strings”, i.e.

public string Name
{
   get { return name; }
   set { this.RaiseAndSetIfChanged(x => x.Name, ref name, value); }
}

I wanted to have something similar in F#. Instead of extension methods, I went the base class route

type ViewModelBase() =
    let propertyChanged = Event<_, _>()
    interface INotifyPropertyChanged with
        [<CLIEvent>]
        member this.PropertyChanged = propertyChanged.Publish

    member private this.OnPropertyChanged p = propertyChanged.Trigger(this, PropertyChangedEventArgs(p))
           
    member this.RaisePropertyChanged (p : obj) =
        match p with
        | :? string as s -> 
                this.OnPropertyChanged s
        | :? Expr as e -> 
                match propertyName e with
                | Some(pi) -> 
                    this.OnPropertyChanged pi
                | None -> ()
        | :? (string array) as a ->
                a
                |> Array.iter (fun propertyName -> this.RaisePropertyChanged propertyName) 
        | :? (Expr array) as a ->
                a
                |> Array.iter (fun propertyExpression -> this.RaisePropertyChanged propertyExpression) 
        | null ->
                this.OnPropertyChanged null
        | _ -> ()

    member this.RaiseAndSetIfChanged ((p : obj), (backingField : 'b byref), newValue) =
        assert (p <> null)

        match EqualityComparer.Default.Equals(backingField, newValue) with
        | true -> false
        | false -> 
            backingField <- newValue
            this.RaisePropertyChanged p
            true

Where the propertyName functions is defined elsewhere as

let rec propertyName quotation =
    match quotation with
    | PropertyGet (_,propertyInfo,_) -> Some(propertyInfo.Name)
    | Lambda (_,expr) -> propertyName expr
    | _ -> None

Note: This function is documented Getting a Property Name as a String in F#

You’ll notice that whilst we can overload methods in an F# type, I’ve gone with pattern matching against types passed into the RaisePropertyChanged method. This just seemed tidier and allowed me to use the same function for passing a null as well (so binding on all properties should update).

This view model base class allows me to raise a property against a “magic string”, against a Expr or against an array of either (useful when I wanted to force multiple readonly properties to update).

The RaiseAndSetIfChanged function expects a non-null property p which can be a string or an Expr.

There might be a better way to do this in F#, but this is what I’ve come up with thus far.

So to use the above code in our view model we would write something like

type MyViewModel() =
    inherit ViewModelBase()

    let mutable name = ""

    member this.Name with get() = name and 
                                set(value) = 
                                    this.RaiseAndSetIfChanged (<@ fun (v : MyViewModel) -> v.Name @>, &name, value) |> ignore

The use of the Code Quotations in F# don’t look quite as good (or terse) as C# and I’m not sure if there’s a better way, but they’re still better than “magic strings”.

Commands

Next up, we need to handle ICommand. I want something akin to ActionCommand, so implemented

type Command(execute, canExecute) =
    let canExecuteChanged = Event<_, _>()
    interface ICommand with
        [<CLIEvent>]
        member this.CanExecuteChanged = canExecuteChanged.Publish
        member this.CanExecute param = canExecute param
        member this.Execute param = execute param

    new(execute) =
        Command(execute, (fun p -> true))

    member this.RaiseCanExecuteChanged p = canExecuteChanged.Trigger(this, EventArgs.Empty)

and in use with have

type MyViewModel() =
    inherit ViewModelBase()

    let mutable name = ""

    member this.Name with get() = name and 
                                set(value) = 
                                    this.RaiseAndSetIfChanged (<@ fun (v : MyViewModel) -> v.Name @>, &name, value) |> ignore

    member this.PressMe = Command(fun p -> this.Name <- "Hello " + this.Name)

Creating a WPF application in F# (a more complete solution)

In my previous post Creating a WPF application in F# I outlined how to create a very basic WPF application using F# and WPF.

I’ve now decided to combine F#, WPF and MahApps metro/modern UI look and feel. In doing so I found a flaw in the previously posted code. First off, the code works fine, but I needed to add some resources to an App.xaml and which point I realized I needed to change the code to handle this. The previous post didn’t use an App.xaml (well it was mean’t to be minimalist solution to using F# and WPF – or at least that’s my excuse).

So I will repeat some of the previous post here in defining the steps to get an F#/WPF/MahApps application up and running.

Note: Please check out the post Build MVVM Applications in F# which outlines how to use the App.xaml file, I will be repeating this here.

Okay, here we go…

  • Create a new project and select F# Application
  • This will be a console application, so next select the project properties and change the Application | Output type from Console Application to Windows Application
  • Add references to PresentationCore, PresentationFramework, System.Xaml and WindowsBase
  • Change the Program.fs to look like this
    open System
    open System.Windows
    open System.Windows.Controls
    open System.Windows.Markup
    
    [<STAThread>]
    [<EntryPoint>]
    let main argv = 
        let application = Application.LoadComponent(
                            new System.Uri("/<Your Assembly Name>;component/App.xaml", UriKind.Relative)) :?> Application
    
        application.Run()
    

    Obviously change <Your Assembly Name> to the name of your compiled assembly name.

  • Using NuGet add MahApps.Metro to the project
  • Add a new item to your project. Unfortunately there’s no XAML file (at least not in the version of Visual Studio I’m testing this on). So simply pick an XML File and give it the name App.xaml
  • In the App.xaml file place the following code
    <Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 StartupUri="MainWindow.xaml">
        <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
    </Application>
    
  • Now add another XML file to the project and name it MainWindow.xaml
  • In the MainWindow.xaml file replace the existing text with
    <Controls:MetroWindow  
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
        Title="MainWindow" Height="350" Width="525">
        <Grid>
        </Grid>
    </Controls:MetroWindow >
    
  • Finally, select the MainWindow.xaml file in the solution explorer and change the file properties Build Action to Resource

Obviously you’ll still need to setup your view model at some point and without the ability to work with partial classes (as F# doesn’t support the concept). We have a couple of options.

I’ve played around with a few ways of doing this and the easiest is to do this in the Startup event of the Application object. In doing this we also need to handle the creation of the MainWindow, so

  • Remove the StartupUri=”MainWindow.xaml” from the App.xaml as we’re going to handle the creation and assignment in code
  • In the Program.fs file, before the application.Run() add the following code
    application.Startup
    |> Event.add(fun _ -> 
                         let mainWindow = Application.LoadComponent(new System.Uri("/WPFFSharp1Test;component/MainWindow.xaml", UriKind.Relative)) :?> Window
                         mainWindow.DataContext <- new MyViewModel()
                         application.MainWindow <- mainWindow
                         mainWindow.Show()
                         )
    

And we’re done. You should now have the styling of MahApps and the creation and setting up with the main window and the main view model.

Creating a WPF application in F#

I wanted to create a bare bones WPF application using F#. There are several templates out there to create WPF apps in F# but they just added too much code from the outset for my liking.

So here are the steps to create a basic WPF F# application

  • Create a new project and select F# Application
  • This will be a console application, so next select the project properties and change the Application | Output type from Console Application to Windows Application
  • Add references to PresentationCore, PresentationFramework, System.Xaml and WindowsBase
  • Change the Program.fs to look like this
    open System
    open System.Windows
    open System.Windows.Controls
    open System.Windows.Markup
    
    [<STAThread>]
    [<EntryPoint>]
    let main argv = 
        let mainWindow = Application.LoadComponent(
                            new System.Uri("/<Your Assembly Name>;component/MainWindow.xaml", UriKind.Relative)) :?> Window
    
        let application = new Application()
        application.Run(mainWindow)
    

    Obviously change <Your Assembly Name> to the name of your compiled assembly name.

  • Add a new item to your project. Unfortunately there’s no XAML file (at least not in the version of Visual Studio I’m testing this on). So simply pick an XML File and give it the name MainWindow.xaml
  • In the MainWindow.xaml file replace the existing text with
    <Window 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
        <Grid>
        </Grid>
    </Window>
    
  • Finally, select the MainWindow.xaml file in the solution explorer and change the file properties Build Action to Resource

And that’s all there is to getting a WPF F# application started.

As F# doesn’t contain all the goodness of WPF templates and code behind etc. out of the box, it still might be better to create a C# WPF application then have all the view model’s etc. in a F# application if you want to, but this is a fairly good starting point if you prefer 100% F#.

Addendum

After working this stuff out and documenting it, I came across a post from MSDN Magazine titled Build MVVM Applications in F# which not only shows a more information on the approach I’ve outlined above, but also how to use F# to create view models etc.

A WPF drag/drop target behavior

I was working on some code whereby the user of the application would drag data from Excel (or a compatible file) onto the application to import the data and I wanted to create a fairly generic method, in WPF, to handle this so that I could apply the code to various controls within the application at different points in the user’s workflow. I also wanted the user interface to change slightly to better inform the user when they were on a control which they could drop data onto. I’m not going to go into how we get the dropped data into the view model or other import mechanism, but will concentrate on the UI interactions.

Note: The UI element of this post was inspired by the GitHub for Windows user interface in that when you drag a URL onto it, the Window changes to indicate it’s in a sort of “drop” mode.

The Behavior

I decided to create a behavior which would handle the various drag and drop events on the associated control. A behavior is a nice abstraction allowing us to augment existing controls with extra functionality or the likes.

As the behavior was to be general to many control types, I chose to create the behavior to work with UIElement’s as these offered the lowest level for hooking into the various drag and drop events.

Let’s look at the initial code for such a behavior

You’ll need to reference System.Windows.Interactivity which can be found in the References | Assemblies | Framework.

public class UIElementDropBehavior : Behavior<UIElement>
{
   protected override void OnAttached()
   {
      base.OnAttached();

      AssociatedObject.AllowDrop = true;
      AssociatedObject.DragEnter += AssociatedObject_DragEnter;
      AssociatedObject.DragOver += AssociatedObject_DragOver;
      AssociatedObject.DragLeave += AssociatedObject_DragLeave;
      AssociatedObject.Drop += AssociatedObject_Drop;
   }

   private void AssociatedObject_Drop(object sender, DragEventArgs e)
   {
      e.Handled = true;
   }

   private void AssociatedObject_DragLeave(object sender, DragEventArgs e)
   {
      e.Handled = true;
   }

   private void AssociatedObject_DragOver(object sender, DragEventArgs e)
   {
      e.Handled = true;
   }

   private void AssociatedObject_DragEnter(object sender, DragEventArgs e)
   {
      e.Handled = true;
   }
}

So the above code is pretty simple. Obviously to be a drop target we need to ensure the associated UIElement is in AllowDrop mode and then handle the events ourselves. We’ll start to implement the specific code next, but before we do let’s see how this would be used in XAML. So within the control declaration of the control we want the behavior associated with (in XAML) we would simply use the following

<i:Interaction.Behaviors>
   <behaviors:UIElementDropBehavior />
</i:Interaction.Behaviors>

Okay, at this point this doesn’t really do a lot.

So the idea is that when the user drags the data over the control a new UI is displayed which displays a nice bitmap and the text “Drop Items Here” or similar. When the user drops the items the UI should switch back to it’s previous state or when the user drags outside/leaves the control it should also switch back to it’s previous state. I decided to implement this UI as an Adorner. So let’s take a look at this code.

The Adorner

We’re going to use some drawing primitives to display our bitmap and text. Let’s jump straight in a look at the code

public class UIElementDropAdorner : Adorner
{
   public UIElementDropAdorner(UIElement adornedElement) : 
      base(adornedElement)
   {
      Focusable = false;
      IsHitTestVisible = false;
   }

   protected override void OnRender(DrawingContext drawingContext)
   {
      const int PEN_WIDTH = 8;

      var adornedRect = new Rect(AdornedElement.RenderSize);

      drawingContext.DrawRectangle(Brushes.White, 
            new Pen(Brushes.LightGray, PEN_WIDTH),    
            adornedRect);

      var image = new BitmapImage(
            new Uri("pack://application:,,,/SomeAssembly;component/Resources/drop.png",   
            UriKind.Absolute));
		
      var typeface = new Typeface(
            new FontFamily("Segoe UI"), 
               FontStyles.Normal, 
               FontWeights.Normal, FontStretches.Normal);
      var formattedText = new FormattedText(
            "Drop Items Here", 
            CultureInfo.CurrentUICulture, 
            FlowDirection.LeftToRight, 
            typeface, 
            24, 
            Brushes.LightGray);

      var centre = new Point(
            AdornedElement.RenderSize.Width / 2, 
            AdornedElement.RenderSize.Height / 2);

      var top = centre.Y - (image.Height + formattedText.Height) / 2;
      var textLocation = new Point(
            centre.X - formattedText.WidthIncludingTrailingWhitespace / 2, 
            top + image.Height);

      drawingContext.DrawImage(image, 
            new Rect(centre.X - image.Width / 2, 
            top, 
            image.Width, 
            image.Height));
      drawingContext.DrawText(formattedText, textLocation);
   }
}

Don’t forget to change the Uri of the image to one within your project resources.

So the key areas in the code (above) are that we need to set IsHitTestVisible to false. If we don’t do this then when we implement the relevant code to tie the behavior and adorner together we’ll find that when the user drags over the control our behavior is associated with, the behavior will display the adorner and the adorner will then intercept the rest of the drag and drop events. This will have the effect of actually causing the control that we’re handle drag and drop on to get a DragLeave event and the behavior will then hide the adorner. Then it’ll get a DragEnter event and display the adorner again – this will causes the adorner to flicker on and off – not ideal. So we want the adorner to ignore events and pass them back to the behavior.

The code in the OnRender, simply displays a PNG with the text “Drop Items Here” below it, centred within the control we’re associating the drag and drop behavior with.

Now we need to tie the behavior and adorner together, i.e. we need the behavior to display the adorner and remove it when either a drop or drag leave event is received. We’re going to create a simple class to manage the interactions with the adorner.

The AdornerManager

So the AdornerManager class is going to be used to simply create an adorner when it’s requried, display it and hide and remove it when it’s not required. Here’s the code…

public class AdornerManager
{
   private readonly AdornerLayer adornerLayer;
   private readonly Func<UIElement, Adorner> adornerFactory;

   private Adorner adorner;

   public AdornerManager(
             AdornerLayer adornerLayer, 
             Func<UIElement, Adorner> adornerFactory)
   {
      this.adornerLayer = adornerLayer;
      this.adornerFactory = adornerFactory;
   }

   public void Update(UIElement adornedElement)
   {
      if (adorner == null || !adorner.AdornedElement.Equals(adornedElement))
      {
         Remove();
         adorner = adornerFactory(adornedElement);
         adornerLayer.Add(adorner);
         adornerLayer.Update(adornedElement);
         adorner.Visibility = Visibility.Visible;
      }
   }

   public void Remove()
   {
      if (adorner != null)
      {
         adorner.Visibility = Visibility.Collapsed;
         adornerLayer.Remove(adorner);
         adorner = null;
      }
   }
}

So this code is pretty simple, we manager the creation of the adorner which is created using the factory method supplied in the constructor. When we create the adorner we associated with the adorner layer on the underlying control and display it. The Remove method simply tidies up – hiding the adorner then removing it.

We now need to revisit the UIElementDropBehavior and get the various events to call the AdornerManager.

Almost complete

The completed code for the UIElementDropBehavior class is listed below

public class UIElementDropBehavior : Behavior<UIElement>
{
   private AdornerManager adornerManager;

   protected override void OnAttached()
   {
      base.OnAttached();

      AssociatedObject.AllowDrop = true;
      AssociatedObject.DragEnter += AssociatedObject_DragEnter;
      AssociatedObject.DragOver += AssociatedObject_DragOver;
      AssociatedObject.DragLeave += AssociatedObject_DragLeave;
      AssociatedObject.Drop += AssociatedObject_Drop;
   }

   private void AssociatedObject_Drop(object sender, DragEventArgs e)
   {
      if (adornerManager != null)
      {
         adornerManager.Remove();
      }
      e.Handled = true;
   }

   private void AssociatedObject_DragLeave(object sender, DragEventArgs e)
   {
      if (adornerManager != null)
      {
         var inputElement = sender as IInputElement;
         if (inputElement != null)
         {
            var pt = e.GetPosition(inputElement);

            var element = sender as UIElement;
            if (element != null)
            {
                if (!pt.Within(element.RenderSize))
                {
                   adornerManager.Remove();
                }
            }
         }
      }
      e.Handled = true;
   }

   private void AssociatedObject_DragOver(object sender, DragEventArgs e)
   {
      if (adornerManager != null)
      {
         var element = sender as UIElement;
         if (element != null)
         {
            adornerManager.Update(element);
         }
      }
      e.Handled = true;
   }

   private void AssociatedObject_DragEnter(object sender, DragEventArgs e)
   {
      if (adornerManager == null)
      {
         var element = sender as UIElement;
         if (element != null)
         {
            adornerManager = new AdornerManager(
                AdornerLayer.GetAdornerLayer(element), 
                adornedElement => new UIElementDropAdorner(adornedElement));
         }
      }
      e.Handled = true;
   }
}

In the above code we create the AdornerManager the first time the DragEnter event occurs and supply it the factory method as AdornerLayer for the control we intend to display the adorner over. In the Drop handler we simply remove the adorner using the AdornerManager and in the DragOver handler we update the adorner.

The DragLeave handler is a little more complex than just removing the adorner when the leave event occurs. This is because I found that the control I was handling drag and drop on appeared to cause the behavior’s DragLeave event to occur which would then cause the adorner to be removed even when the mouse was still over the control, so to stop this happening we check whether the the mouse is now outside of the control we’re handling drag and drop on before removing the adorner. This stops the flickering on and off of the adorner.

I’ve created a very simply extension method used in the code above (the Within method). Here’s the code

public static class PointExtensions
{
   public static bool Within(this Point pt, Rect r)
   {
      return pt.X >= r.X && 
         pt.Y >= r.Y && 
         pt.X < r.Width && 
         pt.Y < r.Height;
   }

   public static bool Within(this Point pt, Size s)
   {
      return pt.Within(new Rect(s));
   }
}

Sample Code

DragAndDropBehavior

AutoMapper Converters

When using AutoMapper, it may be that we’re using types which map easily to one another, for example if the objects being mapped have the same type for a property or the type can be converted using the standard type convertes, but what happens when things get a little more complex?

Suppose we have a type, such as

public class NameType
{
   public string Name { get; set;
}

and we want to map between a string and the NameType, for example

var nameType = Mapper.Map<string, NameType>("Hello World");

As you might have suspected, this will fail as AutoMapper has no way of understanding how to convert between a string and a NameType.

You’ll see an error like this


Missing type map configuration or unsupported mapping.

Mapping types:
String -> NameType
System.String -> AutoMapperTests.Tests.NameType

Destination path:
NameType

Source value:
Hello World

What we need to do is give AutoMapper a helping hand. One way is to supply a Func to handle the conversion, such as

Mapper.CreateMap<string, NameType>().
	ConvertUsing(v => new NameType { Name = v });

alternatively we can supply an ITypeConvert implementation, such as

public class NameConverter :
   ITypeConverter<string, NameType>
{
   public NameType Convert(ResolutionContext context)
   {
      return new NameType {Name = (string) context.SourceValue};
   }
}

and use in like this

Mapper.CreateMap<string, NameType>().
   ConvertUsing(new NameConverter());

AutoMapper Profiles

When creating mappings for AutoMapper we can easily end up with a mass of CreateMap methods in the format

Mapper.CreateMap<string, NameType>();
Mapper.CreateMap<NameType, string>();

An alternate way of partitioning the various map creation methods is using the AutoMapper Profile class.

Instead we can create profiles with as fine or coarse granularity as you like, here’s an example

public class NameTypeProfile : Profile
{
   protected override void Configure()
   {
      CreateMap<string, NameType>()
      CreateMap<NameType, string>();
   }
}

To register the profiles we need to then use

Mapper.AddProfile(new NameTypeProfile());

which can also become a little tedious, but there’s an alternative to this…

AutoAutoMapper Alternative

So instead of writing the code to add each profile we can use the AutoAutoMapper in the following way

AutoAutoMapper.AutoProfiler.RegisterProfiles();

this will find the profiles within the current assembly or those supplied as params arguments to the RegisterProfiles method for us. This way the profiles are registered for you.