Monthly Archives: January 2014

Caliburn Micro’s message bus (event aggregator)

Most MVVM frameworks come with some form of message bus. A means to send messages from one class to any classes wishing to listen for such messages. Ofcourse in a MVVM world those classes might be view models also.

In Caliburn Micro this message bus implementation is known as the event aggregator which is defined by the IEventAgreggator interface.

A class wishing to subscribe to events simple get passed an IEventAggregator as calls the subscribe method as follows

public MyViewModel(IEventAggregator eventAggregator)
{
   eventAggregator.Subscribe(this);
}

In this example we’re using the constructor and in this case, I’m using the Ninject bootstrapper which we looked at in a previous post, to inject the IEventAggregator into the constructor.

Obviously we need to add some code to actually handle any events as this solely subscribes to the aggregator, so for the sake of argument we’ll assume we have an event class which looks like the following

public class MyMessageEvent
{
   public MyMessageEvent(string message)
   {
      Message = message;
   }

   public string Message { get; provate set; }
}

And now on our view model we implement IHandle

public class MyViewModel : PropertyChangedBase, IHandle<MyMessageEvent>
{
   public void Handle(MyMessageEvent message)
   {
      // do something with the event
   }
}

Now we need something to publish events…

If we create another view model and again pass the IEventAggregator into the constructor as per

public class MyViewModel : PropertyChangedBase
{
   private IEventAggregator eventAggregator;

   public MyViewModel(IEventAggregator eventAggregator)
   {
      this.eventAggregator = eventAggregator;
   }

   public void PublishMessage()
   {
      event.Publish(new MyMessageEvent("Hello"));
   }
}

List basics in F#

In a previous post I touched on F# lists, now let’s look a little further into the F# lists.

Note: Also check out Lists (F#) for a far more comprehensive view of F# lists

The MSDN documentation states that F# lists are implemented as singly linked lists.

Creating Lists

First off we can create a list using square brackets and semi colon delimiters, for example

let list = ["One"; "Two"; "Three"]

This creates a string list using type inference, i.e.

val list : string list = [“One”; “Two”; “Three”]

Had we wanted we could also create a list with a type hint mirroring this line (note the string list type hint)

let list : string list = ["One"; "Two"; "Three"]

We can also define this list without the semi-colon delimiter, instead using newlines as per

let list = [
   "One"
   "Two"
   "Three"]

We can declare an empty list as follows

let list = []

We can also declare lists using the range operator, for example

let list = ['a' .. 'z']

Whilst we can define a list of data as above, we can also generate the list in the following way

let list = [for i in 'A' .. 'Z' -> i]

Operators

The double colon :: operator takes a left hand argument as a single item and the right hand side as a list and creates a new list which is made up of the left hand argument and then right hand list appended to it. So, for example

let original = [1; 2; 3]
let list = 0 :: original

will result in list being [0; 1; 2; 3]

We can also concatenate lists using the @ operator, for example

let right = [1; 2; 3]
let left = [3; 2; 1]

let combined = left @ right

This results in a new list which looks like [3; 2; 1; 1; 2; 3]

Operator overloading in F#

F# allows us to override existing operators and even create our own. There are two types of operators, prefix and infix.

Prefix operators are those which take one operand. Infix operators take two arguments.Unlike C# both operands in an infix operator must be of the same type.

Along with overloading existing operators we can create custom operators using a single or multiple characters from the following !$%&+-,/<=>?@^|~

For example, let’s define a global operator !^ which will calculate the square root of a floating point number

let inline (!^) (a: float) = Math.Sqrt(a)

and in usage

let sqrt = !^ 36.0
printfn "Sqrt %f" sqrt

An infix operator is declared taking two arguments, so here’s an example of a value to the power n, which we’ll use the operator ++ which can be defined as

let inline (++) (x: float) (y: float) = Math.Pow(x, y)

and in usage

let a = 10.0 ++ 2.0

When declaring operators on a type (as opposed to globally) we have the following

type MyClass2(x : int) =
    member this.value = x
    static member (~+) (m : MyClass2) = 
        MyClass2(m.value + 1)
    static member (+) (m : MyClass2, v : int) = 
        MyClass2(m.value + v)

// usage 

let m = new MyClass2(1)
let n = m + 5

Unit testing in F#

There are several libraries for writing unit tests in F#. FsUnit allows us to reuse xUnit, NUnit or MbUnit.

So using FsUnit with xUnit do the following

  1. Add a new Library project
  2. Using NuGet, add a reference to FsUnit.Xunit

Now we can write our tests using the following

open FsUnit.Xunit
open Xunit

module Tests =

   [<Fact>]
   let ``add two numbers`` () =
      let m = new Mathematics()
      m.add 1 3 |> should equal 4

using backtick notation for identifers is useful for helping us write human readable test names.

Pattern matching in F#

Pattern matching allows us to use a more powerful form of if..then..else or switch/select case type statements.

We declare a pattern matching implementation as follows

let option o =
   match o with
   | 1 -> "item 1"
   | 2 -> "item 2"
   | _ -> "unkown"

// usage
let choice = option 2

The _ is used as a wildcard character, i.e. anything not matching the patterns above..

We can also add matching along the lines of

let option o =
   match o with
   | o when o <= 0 -> failwith "value must be greater than 0"
   // other patterns

You can also match to more than one pattern as per

let option o =
   match o with
   | 1 | 2 -> "one or two"
   // other patterns

We can also pattern match on tuples for example

let options tuple =
match tuple with
   | "one", 1 -> "got one"
   | "two", 2 -> "got two"
   | _, _ -> "unknown"

// usage
let k = options ("one", 1)
printfn "%s" <| k 

Better still we can ignore part of a tuple

 let options tuple =  match tuple with    | "one", _ -> "got one"
   | _, 2 -> "got two"
   | _, _ -> "unknown"

// usage
let k = options ("?", 2)
printfn "%s" <| k 

or we could use the following to denote tuples

 let options (a, b) =     match (a, b) with    | "one", _ -> "got one"
   | _, 2 -> "got two"
   | _, _ -> "unknown"

let k = options ("?", 2)
printfn "%s" <| k

Type pattern matching

We can also use the pattern matching to match against the type of the value passed to it, for example

<![CDATA[
let value = 3.12f

let y =
   match box value with
   | :? System.Int32 -> "integer"
   | :? System.Single -> "float"
   | :? System.String -> "string"
   | _ -> "undefined"

printfn "%s" <| y
]]>

In the above we need to use box, alternatively we can use the following

let y (o: obj) =
   match o with
   | :? System.Int32 -> "integer"
   | :? System.Single -> "float"
   | :? System.String -> "string"
   | _ -> "undefined"

printfn "%s" <| string y

Note: Here, instead of creating a let statement to get the result from the match I’m supplying it directly to the printfn function. Interestingly whilst the return is a string and the printfn I set to output a string, at this point it’s a generic string and we need to cast it directly to a string (non-generic)