Strange white on black numbers during debug in Visual Studio 2015

When running a Universal Windows application in debug mode within Visual Studio 2015 I noticed some “strange” white numbers on a black background adorning my application window (and in the case of a desktop application displayed on the top right of the screen).

It seems these are enabled via the App.xaml.cs file, within the OnLaunched method (the code in some cases may appear in the App() constructor according to the documentation) there’s the following code

#if DEBUG
   if(System.Diagnostics.Debugger.IsAttached)
   {
      this.DebugSettings.EnableFrameRateCounter = true;
   }
#endif

See also DebugSettings.EnableFrameRateCounter property.

As stated within the above link, this causes an overlay of two sets of numbers. Those in the upper left of the screen/Window relate to the application being debugged those in the upper right apply to the overall system.

Basically the left number is the app’s UI frame rate in frames per second and the right number is the CPU usage of the app’s UI thread per frame in milliseconds.

Getting started with Paket

For a while now I’ve been meaning to have a play with Paket and I’ve finally found some time to try it out.

What is Paket?

Paket is a package management tool along the lines of NuGet. In many ways you think of it as NuGet plus some extra goodies.

Like NuGet, you can download/update/install NuGet packages, but on top of that you have the ability to download/update/install files from GitHub or from the Gist repositories or single files from an HTTP resource. This is so useful, especially when you have files that maybe you don’t want to create assemblies around to reuse, but instead just want to include the files in your project in their minimal state, i.e. just as source code (or any other file type you like).

Jumping straight in

Okay, enough chat, let’s get started.

I’m going to create a solution in Visual Studio named PaketTest, mine’s a console application but it really doesn’t matter as we’re just going to walk through the quickest and simplest way to get up and running with Paket. We’re using this solution solely as a place holder so we can see our dependencies referenced and files loaded – to get a feel for how things work and look.

When the solution’s loaded we’re going to use NuGet to grab the paket.exe. The Paket website’s tutorial mentioned getting Paket EXE and/or the bootstrapper from GitHub, but in some scenarios you might be locked down by your companies download policy to not be able to download EXE’s. So either grab the bootstrapper and use that to download paket.exe or use NuGet to get it.

So follow these steps and we’ll be up and running in now time

  • From Package Manage Console in your Visual Studio solution, run Install-Package Paket
  • From a command prompt, navigate to the root folder of your solution
  • Create the directory .paket
  • You can either copy paket.exe to this location or run it from the packages folder, I’ve copied mine here as it’s an easier path to type each time
  • In the solution root folder create the file paket.dependencies. Next, add the following to that file
    source https://nuget.org/api/v2
    
    nuget Ninject
    
    github putridparrot/MusicTheory Theory.xml
    
    gist putridparrot/b3968f23bdabc86a6777 MemoryInformation.cs
    

    Obviously feel free to replace NInject and the putridparrot GitHub and Gist repositories/files with your own, but as I want to demo these three options, I know that there are files in those locations that we can download.

    The dependencies file is used to get the dependencies from the various locations but does not automatically add these to your solution, that’s covered in the next step.

  • Now we need to create another new file (again in the root folder of the solution) named paket.references. In here place the following code
    NInject
    
    File:Theory.xml
    File:MemoryInformation.cs
    

    This file is what Paket uses to actually add references and files to your solution. As you can see we’re basically saying we want to add the references NInject to our solution and the files listed (with the File: prefix) will be added to a paket-files solution folder. If you’d prefer the files are placed in the root folder or your solution, follow the file name with a . for example

    NInject
    
    File:Theory.xml .
    File:MemoryInformation.cs .
    

    Note: We can also specify a folder in our solution for any files, simply replace the . in the above examples with a folder name, for example

    NInject
    
    File:Theory.xml Data
    File:MemoryInformation.cs Source
    
  • Now we’ve got the configuration in place, run (from the command line in the root of the solution) .paket\paket.exe install.

    This will run the Paket application, which will read the .dependencies file and download the NuGet package NInject and the file Theory.xml from GitHub and the Gist file MemoryInformation.cs. It will then read the .references file (if one exists) to add the references for NInject and will add the two files Theory.xml and MemoryInformation.cs. Depending upon whether you used the . or not, the files will either be in the root of the solution or the paket-files solution folder or a folder you’ve specified.

What’s this paket.lock file

When you run the paket.exe install command you’ll notice a new file added to the root folder, named paket.lock. Mine looks like this

NUGET
  remote: https://nuget.org/api/v2
  specs:
    Ninject (3.2.2)
GITHUB
  remote: putridparrot/MusicTheory
  specs:
    Theory.xml (3383d5e239cf64fa8e65ada252fe08ae5764e36c)
GIST
  remote: putridparrot/b3968f23bdabc86a6777
  specs:
    MemoryInformation.cs (4368713d0b2c0c969be01e9309db818f67a65d53)

To quote “The paket.lock file”, this file “records the concrete dependency resolution of all direct and transitive dependencies of your project”. This file should be checked into your source repos. (along with the other two files) for other developers to use as it will ensure that the same versions of packages are loaded. i.e. if NInject (for example moves forward to version 4.0 this file ensures we’re all still on the same version).

Not covered in the above steps (mainly as I haven’t had need to use it so far), but you can also add a file via an HTTP resource to the dependencies using

http http://someurl/Myfile.cs

and then reference the file in the normal way in the references file, i.e.

File:MyFile.cs

Core paket commands

I’m going to cover some core paket commands here

paket.exe help

As you’d expect this will list all the currently available commands for paket and can be invoked using help or ? or a few other ways which you can find yourself by typing paket help.

paket.exe install

We’ve already covered this, but to document this, the install command is used to download the dependencies specified within the paket.dependencies file or the paket.lock file (remember if the paket.lock file is not supplied it will be generated via the install command).

paket.exe outdated

What if a dependency has a new version available ? We can run the outdated command to ask paket to report on whether any packages have been updated, i.e. are there any newer versions. This command does not actually update anything, it’s there to tell us if we might need to update.

packet.exe update

Unlike outdated, the update command will not only check for newer versions of packages but will download them and update any that are declared in the paket.references file.

paket.exe convert-from-nuget

If you’re working on a solution that is already using NuGet and you want to convert to paket you can use the convert-from-nuget command. See paket convert-from-nuget for a full list of steps/information on this command.

paket.exe restore

Previously I mentioned checking the paket.lock file into the source repos. Now if I’ve just joined a project and I need to restore the packages, I can run the restore command which works in a similar way to NuGet restore in that it will download the relevant packages and files based upon the information in the lock file and set my solution up accordingly. This command will use the .lock file to ensure it gets the same versions so I would now be in sync with those who checked this file in.

References

Paket on GitHub
The Paket website

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

lookup index.docker.io no DNS servers error

I’ve been learning Docker lately and all was working well, then today I started seeing the following error lookup index.docker.io no DNS servers error when trying to pull a docker container from Docker Hub. Very strange as this worked fine previously.

For the record, I was able to use apt-get to update packages and I could ping the index.docker.io address, so I’m not sure what changed to make this break.

Anyway to solve the problem we can simply append dns-nameservers to the file /etc/network/interfaces

For example

auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static
address 192.x.x.x
netmask 255.255.255.0
gateway 192.x.x.1
dns-nameservers 8.8.8.8 8.8.4.4

In the above I’ve added the loopback and two google name servers to the interfaces file.

To activate these changes (without a reboot) just use

ifdown eth0 && ifup eth0

Exception handling policies with Polly

I just came across the Polly library whilst listening to Carl Franklin’s “Better know a framework” on .NET Rocks and it looks to be a perfect fit for use on a project I’m working on which makes calls to various services and thus can encounter various types of exceptions, some which might succeed if retried after a certain amount of time (for example).

To install Polly via NuGet simple use

Install-Package Polly

What is it?

Check out Polly on GitHub

So basically Polly allows you to create a Policy which can then be used to execute against a method which might have exceptions – so for example maybe the method calls a webservice and as well as possibly getting exceptions from the webservice may have exceptions on the client such as the service being down or the likes.

A policy basically defines which exceptions to handle, what to do when an exception occurs and you can tell Polly to retry the original method or break and stop the method being called again until a certain timespan has passed.

A policy is created using a fluent style interface, so let’s take a look at some simple examples

Note: Polly on GitHub has many examples of using the code which are more far better and complete than I intend to show here.

var policy = Policy
   .Handle<ArgumentOutOfRangeException>()
   .Retry();

try
{
   policy.Execute(() => service.Calculate(a, b));
}
catch(Exception e)
{
   Console.WriteLine(e.Message);
}

In the above example we create a policy object using the PolicyBuilder (fluent) syntax. We need to end the method calls with Retry, RetryForever, CirtcuitBreaker or WaitAndRetry (or the Async variants) to get a Policy object created. We are using an empty Retry means Retry the method invoked via the Execute method once. We can also specify a number of retries if we want. So if the call to service.Calculate fails with an ArgumentOutOfRangeException Polly will execute the method once more and if it still fails we will get the exception propagated back into our application code, hence we still need to look to handle exceptions in our own try..catch block or ofcourse via our application’s unhandled exception mechanism.

In the code sample, we have only listed a single exception that the policy attempts to retry on, but we can list multiple exceptions that we want to retry on and/or we can supply functionality to the handler to decide what to do when an exception occurs, which obviously makes the whole exception handling/retry mechanism more configurable.

Handle and Or can do a little more

So the Handle and therefore the Or methods can also do a little more than just handle the exception, they also allow us to supply a function which takes the exception and returns a boolean. From this we can be more selective of the exceptions we handle, for example

var policy = Policy
   .Handle<ArgumentOutOfRangeException>(ex =>
      ex.ParamName == "a")
   .Retry();

In the code above, we’re simply saying, if the exception param name is “a” then retry executing the method otherwise the exception is propagated without any retries etc.

Handling multiple exceptions

To handle multiple exceptions we write the following

var policy = Policy
   .Handle<ArgumentOutOfRangeException>()
   .Or<DivideByZeroException>()
   .Or<SomeOtherException>()
   .Retry();

In the above we list the three exception types we want to retry the execution method on receiving.

Execute the method

The Policy Execute method is what ultimately calls the code which we’re wrapping in the policy. So the following is calling our service’s Calculate method and it’s within this block that any retries etc. occur.

policy.Execute(() => service.Calculate(a, b));

We can also handle calls to functions with return values using

var result = policy.Execute(() => service.Calculate(a, b));

There’s also the ability to pass some data as context through the policy (discussed in part a little later) when specifying methods to handle context we instead get a ContextualPolicy object back and this allows us to pass a dictionary of string/object key/values into the Execute method which can then be used within the policy user-defined code.

Retry and retry again

The Retry syntax in Polly allows us to do retry once, retry multiple times and more, so let’s look at some code samples of this method and see what each does

Policy.
   .Handle<SoapException>
   .Retry(); // retry once

Policy.
   .Handle<SoapException>
   .Retry(3); // retry 3 times

Policy
   .Handle<SoapException>
   .Retry((ex, count) =>
   {
       // maybe log the exception or do something else
   }); // retry and call an action on each retry, 
       // supplying the exception and retry count

Policy
   .Handle<SoapException>
   .Retry(3, (ex, count) => // retry 3 times
   {
       // maybe log the exception or do something else
   }); // retry and call an action on each retry, 
       // supplying the exception and retry count

// 

Policy
   .Handle<SoapException>
   .Retry((ex, count, context) =>
   {
       // maybe log the exception or do something else
   }); // retry and call an action on each retry, 
       // supplying the exception and retry count

Policy
   .Handle<SoapException>
   .Retry(3, (ex, count, context) => // retry 3 times
   {
       // maybe log the exception or do something else
   }); // retry and call an action on each retry, 
       // supplying the exception and retry count

The last two retry methods create a ContextPolicy which allows us to pass context information via the Execute method. So if you want to pass some for of context information in a dictionary of string, object key/values. You can do so via this mechanism.

RetryForever – does what it says

The RetryForever method does exactly what it says and will simply keep retrying executing the method, there are currently three overloads of this method

Policy
   .Handle<SoapException>
   .RetryForever(); // just keeping retrying

Policy
   .Handle<SoapException>
   .RetryForever(ex =>
   {
       // possibly log the exception ?
   }); // just keeping retrying but allows 
       // us to do something on each retry

Policy
   .Handle<SoapException>
   .RetryForever((ex, context) =>
   {
       // possibly log the exception ?
   }); // just keeping retrying but allows
       // us to do something on each retry
       // with context

WaitAndRetry, pause and then try it again

The WaitAndRetry method allows us to not only retry but also to build in a wait period, so for example when calling something like a webservice we might make a service call and if a specific exception occurs, maybe specifying the service is unavailable, we might allow the method to be executed again (retried) after a timeout period. Better still we can supply multiple timespans to the WaitAndRetry method, so for example the first time we might retry after 5 seconds, but if the service is still not available, then we might reduce the timeout (or increase it) then decrease or increase again before we stop retrying.

Policy
   .Handle<SoapException>
   .WaitAndRetry(3, count =>
   {
      return TimeSpan.FromSeconds(5);
   }); // retry 3 times with a 
       // wait of 5 seconds each time

Policy
   .Handle<SoapException>
   .WaitAndRetry(3, count =>
   {
      return TimeSpan.FromSeconds(5);
   }, (ex, ts) =>
   {
       // action called on each retry
   }); // retry 3 times with a 
       // wait of 5 seconds each time

Policy
   .Handle<SoapException>
   .WaitAndRetry(3, count =>
   {
      return TimeSpan.FromSeconds(5);
   }, (ex, ts, context) =>
   {
       // action called on each retry
       // with context
   }); // retry 3 times with a 
       // wait of 5 seconds each time

Policy
   .Handle<SoapException>
   .WaitAndRetry(3, new[]
   {
      TimeSpan.FromSeconds(10),
      TimeSpan.FromSeconds(5),
      TimeSpan.FromSeconds(1)
   }); // retry 3 times using
       // supplied timespans

Policy
   .Handle<SoapException>
   .WaitAndRetry(3, new[]
   {
      TimeSpan.FromSeconds(10),
      TimeSpan.FromSeconds(5),
      TimeSpan.FromSeconds(1)
   }, (ex, ts) =>
   {
       // action called on each retry  
   }); // retry 3 times using
       // supplied timespans

Policy
   .Handle<SoapException>
   .WaitAndRetry(3, new[]
   {
      TimeSpan.FromSeconds(10),
      TimeSpan.FromSeconds(5),
      TimeSpan.FromSeconds(1)
   }, (ex, ts, context) =>
   {
       // action called on each retry  
       // with context
   }); // retry 3 times using
       // supplied timespans

CircuitBreaker, stop calls whilst it’s broken

The CircuitBreaker method allows us to mark a method call as broken and ensure we do not call it again. Ofcourse we probably will want to call the method again at some point and thus we can supply the number of exceptions to allow before the circuit breaker kicks in and a TimeSpan signifying the duration of the break, i.e. before it’s auto resets and we can execute the method again.

Policy
   .Handle<SoapException>
   .CircuitBreaker(3, TimeSpan.FromSeconds(10));

So in the above code we don’t automatically retry or anything like that. The policy will maintain state so that if we call the executed method and it exceptions, then the exception will propagate through to the caller (as it normally would with such an exception), however if when then execute the method again two more times and they both fail, then the circuit is “opened” and no further calls will be accepted, meaning we’ll get get BrokenCircuitExceptions until the duration of the break resets the circuit to closed.

Getting started with Docker

I’ve been wanting to try out Docker for a while. Finally got my Ubuntu 14.04 server up and running, so now’s the time.

First off I installed docker as per the instruction on How to Install Docker on Ubuntu 14.04 LTS.

What version of Docker am I running?

Simple enough, just type docker version. Assuming the docker daemon is running you should see various bits of version information.

I’m currently running Client version 1.0.1

How to search for container images

We’re going to start by simply trying to find an existing images that we can pull onto our server, so typing docker search <name of image> will result in a list of images found with a match on the supplied image name.

For example docker search mongodb will return a list from the Docker hub of images with mongodbInstalling an image

Once we’ve found the image we want we need to “pull” it onto our machine using docker pull <name of image>

So let’s pull down the official mongodb image

docker pull mongo

This command will cause docker to download the current mongo image. Once completed you will not need to pull the image again it will be stored locally.

Hold on where are images stored locally?

Run docker info to see where the root directory for docker is, as well as information on the number of images and containers stored locally.

Runnning a container

Once we’ve pulled down an image we can run and application within the container, for example docker run <name of image> <command to run>

Let’s run our mongodb container by typing the following

  • docker run –name some-mongo -d mongo
  • docker run -it –link some-mongo:mongo –rm mongo sh -c ‘exec mongo “$MONGO_PORT_27017_TCP_ADDR:$MONGO_PORT_27017_TCP_PORT”‘

In the above some-mongo should be replaced with the name you want to use.

Note: These command lines will run mongodb in interactive mode, i.e. we will be placed into the mongodb shell.

Updating the container

An image itself may be based upon an OS, such as Ubuntu. So we can actually run commands on the operating system in the container, for example apt-get. Installing software into an OS container is cool but we will then want to persist such changes to the container.

Whilst the changes have been made, they are not yet persisted to the containter. To persist our changes we need to commit them.

First we need to find the ID of the container, for example running docker ps -l, then we save the changes using docker commit <ID> <new container name>.

You needn’t type the whole ID from the call to docker ps -l, the first three or four characters (assuming they’re unique) will suffice.

The value returned from the commit is the new image id.

Inspect

We can view more extensive information on a container by using docker inspect <ID>. Remember the ID can be found using docker ps.

Inspect allows is to see all sorts of information including the image’s IP address.

Pushing an image to the Docker Hub Registry

Once we’re happy with our image we can push it to the docker hub to allow others to share it. Simply use docker push <name of image>.

To find the images on your machine simply use docker images.

Removing all containers and all images

We can use docker’s ps command along with the docker rm command

docker rm $(docker ps -a -q)

to remove all containers and we can use the docker rmi command to remove images as follows

docker rmi $(docker images -q)