Monthly Archives: May 2015

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)