Phillip Trelford's Array

POKE 36879,255

F# operator overloads for WPF dependency properties

When creating a desktop application with WPF using F# there are a number of options:

For small desktop applications, the last option, creating WPF elements directly from F# can produce good self-contained code, but at time is a little less readable than the XAML equivalent. Lets consider placing a button bound to a command on a grid at a certain position.

The XAML fragment might look like this:

<Button Content="_1" Command="{Binding Key1Command}"
        Grid.Column="0" Grid.Row="2"/>

 

Code equivalent:

let button = Button(Content="_1")
button.SetBinding(Button.CommandProperty,Binding("Key1Command")) |> ignore
Grid.SetColumn(button,0)
Grid.SetRow(button,2)

 

Code equivalent using (+) operator overloads to add the dependency properties:

Button(Content="_1") + Button.Command(Binding "Key1Command") 
    + Grid.Column 0 + Grid.Row 2 

 

The glue is just a couple of classes that define a dependency property and value/binding pair with a (+) operator overload that sets the value on the target WPF element.

For Dependency Property values:

type DependencyPropertyValuePair(dp:DependencyProperty,value:obj) =
    member this.Property = dp
    member this.Value = value
    static member (+) 
        (target:#UIElement,pair:DependencyPropertyValuePair) =
        target.SetValue(pair.Property,pair.Value)
        target

 

For Dependency Property bindings:

type DependencyPropertyBindingPair(dp:DependencyProperty,binding:BindingBase) =
    member this.Property = dp
    member this.Binding = binding
    static member (+) 
        (target:#FrameworkElement,pair:DependencyPropertyBindingPair) =
        target.SetBinding(pair.Property,pair.Binding) |> ignore
        target

 

Finally relevant WPF types must be extended with helper methods (note: this could be code generated):

type Grid with
    static member Column (value:int) =
        DependencyPropertyValuePair(Grid.ColumnProperty,value)
    static member Row (value:int) =
        DependencyPropertyValuePair(Grid.RowProperty,value)

 

Attached is a sample calculator VS2010 project showing the mechanism in action.

Calculator

Calculator.zip (3.57 kb)

Trading on IM with F#

Last week saw the inaugural meeting of the London based F# user group – F#unctional Londoners. The group already has over 100 members! There were 2 talks Numerical Optimisation and Instant Messaging with F#, with Naoufel El Bachir giving a really good talk on Numerical Optimization and myself on Trading with Instant Messaging (IM). We had a great turn out, managing to fill the allocated room with around 50 F# enthusiasts, and there was some great discussion after both after the talks and then at a local pub.

A little positive feedback I’ve from the event :) :

loved your presentation on F#!

… that was awesome.

The slides from my Trading on IM talk will be attached to this post, and the video/podcast should be appear on the Skills Matter website. I’ll also attach the 100 lines of code for shopping checkout sample, that works with a barcode scanner, I showed at the start of my presentation.

In the talk I tried to introduce F# agents and asynchronous workflows. If you are interested in learning more please take a look at the following excellent resources:

Next week there is a very interesting talk to look forward to by Rob Pickering, author of Beginning F#, on Language Orientated Programming to target the GPU. And on the horizon we’re expecting in June to see Thomas Petricek, author (with Jon Skeet) of Real-world Functional Programming with examples in F# and C#. Finally, If you’d like to do a talk please do get in touch.

Trading on IM final.pptx (604.82 kb)

Checkout.zip (3.57 kb)

UML Sequence Diagram: F# Script

A UML Sequence diagram can be a great tool for modelling interaction:

UML sequence diagrams model the flow of logic within your system in a visual manner, enabling you both to document and validate your logic, and are commonly used for both analysis and design purposes.  Sequence diagrams are the most popular UML artifact for dynamic modeling, which focuses on identifying the behavior within your system.

Yesterday I fancied moving some hand drawn diagrams to mouse drawn form; but instead found myself battling against a somewhat stubborn and forgetful modelling tool. It left me wondering if there might be an easier way to do this; perhaps by separating the concern of model description from layout. A few moments later I had a description language using an F# class and an F# discriminated union:

type Object(name) =     
    member this.Name = name    

type SequenceAction =
    | Activate of Object
    | Deactivate of Object
    | MessageCall of string * Object * Object
    | MessageAsync of string * Object * Object

Together the Object and SequenceAction types describe an internal Domain Specific Language (DSL) for Sequence Diagrams.

The following is a simple restaurant sample definition (taken from Wikipedia) using the DSL:

let fred = Object("Fred\r\nPatron")
let bob = Object("Bob\r\nWaiter")
let hank = Object("Hank\r\nCook")
let renee = Object("Renee\r\nCashier")
let objects = [fred;bob;hank;renee]   
let actions = 
    [
    MessageCall("order food",fred,bob)
    MessageCall("order food",bob,hank)
    MessageCall("serve wine",bob,fred)
    MessageCall("pickup",hank,bob)
    MessageCall("serve food",bob,fred)
    MessageCall("pay",fred,renee)
    ]

 

Onto the layout, and the .Net Framework has the necessary batteries included to easily do this using either WPF or Silverlight with the:

To get started I used Visual Studio 2010’s WPF XAML designer for prototyping the layout. Then several hours of hacking later I had an F# script (attached) for drawing basic diagrams.

The following was generated using the simple restaurant description above:

simple restaurant uml sequence diagram sample

The colouring of the objects was achieved by extending the Object to allow arbitary dynamic properties to be set which can later be fed to the control:

type DynamicObject () =
    let properties = System.Collections.Specialized.HybridDictionary()
    member this.Item 
        with get (index:string) = properties.[index] 
        and set (index:string) (value:obj) = properties.[index] <- value
    member this.Items =        
        let keys = seq { for key in properties.Keys do yield key :?> string }
        let values = seq { for value in properties.Values do yield value }
        Seq.zip keys values

// Define dynamic lookup get and set operators
let (?) (o:DynamicObject) (property:string) = 
    o.[property]
let (?<-) (o:DynamicObject) (property:string) (value:'a) = 
    o.[property] <- value

type Object(name) =  
    inherit DynamicObject()   
    member this.Name = name    

 

The object’s background colours are set thus:

fred?Background <- Brushes.LightGreen
bob?Background <- Brushes.LightBlue
hank?Background <- Brushes.LightBlue
renee?Background <- Brushes.Pink

 

Conclusion

Whiteboard and paper are still probably the best tools for modelling sequence diagrams. However the DSL approach does have the advantage of allowing easy insertion of objects and messages without the pain of manual layout (constant erasing and redrawing).

Resources

SequenceDiagram.fsx (11.97 kb)