Phil Trelford's Array
POKE 36879, 255

F# Type Providers

March 23, 2014 16:14 by phil

Type Providers are a mature language feature of F# 3 that provide instant typed access, with code completion, to a wide variety of data sources, without requiring code generation. As a language feature, F# Type Providers are cross platform, meaning they can be accessed on Windows via .Net, or on Mac and Linux using the Mono runtime.

If you’re interested in using Type Providers pop down to Skills Matter this Thursday for a Type Provider Treasure Hunt with Tomas Petricek, or Creating Type Providers Hands On with Michael Newton on May 1st.

Much Text

CSV, JSON and XML Type Providers are all available from the community open source FSharp.Data project.

What’s the weather like in London now?

type Weather = JsonProvider< "weather.json" >
let url = "http://api.openweathermap.org/data/2.5/weather?units=metric&q="
let weather = Weather.Load(url+"London")
weather.Main.Temp

Nuget stats on FSharp.Data from an HTML table?

type NugetStats = HtmlProvider<"https://www.nuget.org/packages/FSharp.Data">
let rawStats = NugetStats().Tables.Table0

Many Database

Early type providers allowed access to SQL databases via a connection string, DBML and EDMX files or Entity framework.

The open source SqlClient provider lets you explore queries, stored procedures, user defined types and functions with intellisense.

Access to MS SQL Server, SQLite, PostgreSQL, Oracle and MySQL with full LINQ support is made possible with Ross McKinlay’s SQLProvider.

Connect to the cloud with Isaac Abraham’s Azure Storage Provider.

Or connect to a community-curated database of well-known people places and things with the Freebase provider:

let fb = FreebaseData.GetDataContext()
let astronomy = fb.Society.Celebrities.``Abused substances``

Very Language

Interop seamlessly with the R statistical programming language with the R Type Provider:

open RProvider.``base``
let v = R.c(1,2,3)

Or Matlab, or Java, or Python.

Or Brainfuck

Such Silly

It all started with Ross’s Choose Your Own Adventure Type Provider, and then there was MineSweeper and Battleships.

Now thanks to James you can enjoy FizzBuzz as a Type Provider too:


Have fun!


Tags:
Categories: F# | .Net | Mono
Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

UK Tech Meets

March 23, 2014 11:13 by phil

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 :)


Tags:
Categories: .Net | C# | F#
Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Foq 1.6

March 21, 2014 06:31 by phil

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.


Tags:
Categories: F# | C# | .Net
Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed