Phillip Trelford's Array

POKE 36879,255

Orleans

Microsoft’s Build 2014 conference is currently in full flow, one of the new products announced is Orleans, an Actor framework with a focus on Azure.

There’s an MSDN blog article with some details, apparently it was used on Halo 4.

Demis Bellot of ServiceStack fame, tweeted his reaction:

I retweeted, as it wasn’t far off my initial impression and the next thing I know my phone is going crazy with replies and opinions from the .Net community and Microsoft employees. From what I can make out the .Net peeps weren’t overly impressed, and the Microsoft peeps weren’t overly impressed that they weren’t overly impressed.

So what’s the deal.

Actors

Erlang has distributed actors via OTP, this is the technology behind WhatsApp, recently acquired for $19BN!

The JVM has the ever popular Akka which is based heavily on Erlang and OTP.

An industrial strength distributed actor model for .Net should be a good thing. In fact Microsoft are currently also working on another actor framework called ActorFX,

The .Net open source community have projects in the pipeline too including:

There’s also in-memory .Net actor implementations with F#’s MailboxProcessor and TPL Dataflow. Not to mention the departed Axum and Retlang projects.

Orleans

From what I can tell, Orleans appears to be focused on Azure, making use of it’s proprietary APIs, so there's probably still a big space for the community's open source projects to fill.

Like Demis I’m not a huge fan of WCF XML configuration and code generation. From the Orleans MSDN post, XML and code-gen seem to be front and centre.

You write an interface, derive from an interface, add attributes and then implement methods, which must return Task<T>. Then you do some XML configuration and Orleans does some code generation magic for hydration/dehydration of your objects (called grains).

Smells like teen spirit WCF, that is methods are king, although clearly I could be reading it wrong.

From my limited experience with actors in F# and Erlang, messages and message passing are king, with pattern matching baked into the languages to make things seamless.

Initial impressions are that Orleans is a long way from Erlang Kansas…

The Good Parts

Building a fault-tolerant enterprise distributed actor model for .Net is significant, and could keep people on the platform where they may have turned with Erik Meijer to the JVM, Scala and Akka otherwise.

Putting async front and centre is also significant as it simplifies the programming model.

C# 5’s async is based on F#’s asynchronous workflows, which was originally developed to support actors via the MailBoxProcessor.

Coroutines

Underneath, Erlang’s processes, F#’s async workflows and C#’s async/await are simply implementations of coroutines.

Coroutines are subroutines that allow multiple entry points for suspending and resuming execution at certain locations. They’ve been used in video games for as long as I can remember (which only goes back as far as the 80s).

Coroutines help make light work of implementing state machines and workflows.

Methods

In Erlang messages are typically described as named tuples (an atom is used as the name), and in F# discriminated unions are typically employed.

Orleans appears to use methods as the message type, where the method name is analogous to an Erlang atom name, or an F# union case name and the parameters are analogous to a tuple. So far so good.

Where they differ is that return values are first-class for methods, and return values feel more like an RPC approach. In fact this is the example given in the article:

public class HelloGrain : Orleans.GrainBase, IHello
{
  Task<string> IHello.SayHelloAsync(string greeting)
  {
    return Task.FromResult("You said: '" + greeting + "', I say: Hello!");
  }
}

Also current wisdom for C# async is to avoid async void... which is why I guess they’ve plumped for Task as the convention for methods with no return value.

Messages

.Net’s built-in binary serialization is bottom of the league for size and performance, hopefully alternative serialization libraries like Google Protocol Buffers will be supported.

Judge for yourself

But these are just my initial impressions, try out the samples and judge for yourself.

UK Tech Meets

Passionate about programming, interested in meeting other like minded individuals?

A good place to start is a local meetup group.

.Net

Here’s my short list of active .Net/Mono related groups in the UK which feature some C#, F# or VB content (let me know if I’ve missed your group):

Group Members
London Unity Usergroup 1074
Windows Phone User Group 850+ (on mailing list)
F#unctional Londoners 742
Software East (Cambridge) 673
London .Net User Group 538
Canary Wharf Dot Net User Group 501
Cambridge Developer’s User Group 355
Norfolk Developers (Norwich) 325
Nottingham Programmers 255
Developer South Coast (Southampton) 241
Functional Bridgton 141
Cambridge DDD Nights 122
Brighton ALT.NET 49
Smart Devs (Hereford) 43
Functional South Coast (Southampton) 37
Craft Coders (Worcestershire) 34
Wales & West Windows Applications Group 25
NxtGen (Birmingham)  
VBUG (Bristol)  
Agile Yorkshire  
Sheffield .Net User Group  
Gloustershire .Net User Group  
Dare Devs (Chesire)  
IWDev (Isle of Wight)  
Windows Phone (Bristol/Cardiff)  
Windows Phone (Manchester)  

 

In the .Net arena, it seems gaming, windows phone, and functional programing are hot right now. Overall there’s a good spread of groups across the regions, with high concentrations in London, Cambridge and the South Coast.

Curiously the London C#/.Net focused user groups appear to be eclipsed by the London Java Community meetup which has close to 4000 members, and PHP London with nearly 3000 members.

Functional

Interest in functional programming has been growing steadily as have related groups in the capitol:

Group Members
London Scala Users’ Group 1405
F#unctional Londoners 742
London Clojurians 540
London Haskell 423
London Erlang Uer Group 377

 

On the F# side, the F#unctional Londoners now meets every 2 weeks and has been growing at a rate of around 100 members every 6 months. Progress is not just confined to London, there’s F# user groups popping up across the globe

Data Science

Data Science and Machine Learning are another growth area, and the many machine learning based sessions have been very popular with the F#unctional Londoners.

Group Members
Data Science London 2980
London Machine Learning 1009
Women in Data 380

Hackers

Hacker News is something of a phenomena, and hacker groups appear to be among the biggest:

Group Members
Hacker News London 5771
Silicon Roudabout 5042
Hacks/Hackers London 2524
DevTank London 926

 

Get Involved

Like pizza, like beer, like learning, there’s a meetup group near you waiting :)

Foq 1.6

Foq is a mature open source .Net mocking library written in F#. It’s raison d'être is to enable F# as a unit testing language, for F#, C# or VB.Net code bases.

Foq is part a rich set of testing tools available to F# developers. Use Foq when unit testing in combination with staple .Net testing frameworks like NUnit and xUnit through to F# specific fluent assertion libraries like FsUnit and Unquote. Combine Foq with AutoFixture to simplify test setup even further.


The name Foq is derived from Moq, with Foq providing a familiar fluent interface:

// Moq from C#
var mock = new Mock<ILoveThisFramework>();
mock.Setup(framework => framework.DownloadExists("2.0.0.0"))
   .Returns(true);
ILoveThisFramework lovable = mock.Object;

// Foq from F#
let lovable = 
   Mock<ILoveThisFramework>()
      .Setup(fun framework -> <@ framework.DownloadExists("2.0.0.0") @>)
      .Returns(true)
      .Create()

The main difference in the setups above is that Moq uses mutation where as Foq is thread safe, favouring method chaining to build an immutable representation of the type.

Foq takes advantage of F#’s code quotations and type inference for shorter setups:

// Mock succinctly with Foq
let lovable =
   Mock.With(fun (framework:ILoveThisFramework) ->
   <@ framework.DownloadExists("2.0.0.0") --> true @>)

Getting Started

Get the latest version of Foq from Nuget or simply include Foq.fs in your test project. An F# script packed with examples is included when you install Foq via Nuget.

Then take a peek at some of the many Foq testing examples on CodePlex:

    New features

Back in April 2013, Foq’s API stabilized at version 0.9, since then new features and bug fixes have been requested via CodePlex, StackOverflow and Twitter.

Many of the requests have come from people testing C# codebases from F# and requiring extensive support for:

Testing C# Code

Foq can be used to mock both interfaces and abstract classes. For abstract classes arguments can be passed to the base constructor when the mock is created:

let mock = Mock<AbstractBaseClassWithConstructorArgs>().Create(7, "seven")
Assert.AreEqual("seven", mock.Name)

In F# multiple return values are easily specified using tuples, in C# out parameters are required. To setup C# methods with out parameters using Foq, simply specify the out arguments as tuples as you would normally from F#:

// Calling a method with out arguments from F#
let (success, value) = dict.TryGetValue("Fred")
// Setting up a method with out arguments using Foq
Mock<IDictionary<string,int>>()
   .SetupByName("TryGetValue").Returns((true, 1))
   .Create()

Testing Events

In F# events are first class, meaning they can be created like objects and passed to functions. To setup an event on an interface:

// Arrange
let event = Event<_,_>() 
let instance = 
      Mock<INotifyPropertyChanged>() 
         .SetupEvent(fun x -> <@ x.PropertyChanged @>).Publishes(event.Publish) 
         .Create() 
// Act 
event.Trigger(instance, PropertyChangedEventArgs("Name"))

Non-standard events can be setup using the SetupEventByName method.

Testing F# Code

Foq provides helpers for quickly mocking a single member be it a property:

Mock<MyAbstractBaseClass>.Property(fun x -> <@ x.MyProperty @>).Returns(1)

or a method (note that arguments do not need to be specified):

Mock<GreetingTime>
    .Method(fun gt -> <@ gt.GetGreeting @>)
    .Returns("Good Night")

Foq can now mock F# specific members with curried arguments e.g.

Mock<ICurry>()
    .Setup(fun curry -> <@ curry.Fun (any()) (any()) @>)
    .Returns(true)
    .Create()

Finally Mock.With now supports return values via functions:

Mock<IFoo>.With(fun foo -> 
    <@ 
        foo.Bar(1) --> 1
        foo.Bar(any()) ---> fun () -> 2
    @>)

What next?

Try F# as a testing language for your .Net code bases and use Foq to mock F# and C# types with ease. Then try web testing with canopy, automated acceptance testing using NaturalSpec, TickSpec or SpecFlow or random testing via FsCheck.