Monday, January 23, 2012

Making F# Windows Phone Development a Little Easier

About a month ago, I announced that most of the existing F# project templates on Visual Studio Gallery had been updated to include support for Visual Studio 11. In that post, I mentioned some new item templates that had been included in the update to the F# XAML Item Templates extension. This post provides a bit more information related to that update.

The F# XAML Item Templates extension was designed to make working with F# + WPF and Silverlight a little eaiser. I provided a brief overview of these features back in June. However, Windows Phone XAML related development was still lacking. The previous approach to adding XAML files was to either create a blank file, change the extension, and manually add the appropriate starting XAML or create the XAML from one of the C# item templates, remove the code-behind files, and tweak the resulting XAML. While neither of these options is extremely time consuming, it can quickly become annoying.

The latest update to this Visual Studio extension reduces this annoyance by providing F# Windows Phone 7 XAML item templates. Once this VSIX is installed, you can add a Windows Phone 7 XAML file by doing the following:

1. In a Windows Phone F# project, proceed with adding a new item as you normally would (i.e. Ctrl+Shift+A).

2. The resulting wizard (shown below) includes several new item templates starting with "F#..." that match the C# versions, but that do not generate C# code-behind files. 



While you still have to write the small amount of F# code to wire this up, it makes life a little bit easier.





Monday, January 16, 2012

developerFusion Article: An Introduction to FSharpx

My article entitled "An Introduction to FSharpx" was published a few days ago. You can find it at http://www.developerfusion.com/article/136179/an-introduction-to-fsharpx.

As mentioned in the article, FSharpx is continually evolving and several new features have been added since I submitted this article. Be sure to head over to the FSharpx GitHub site to see what's new.


Sunday, January 8, 2012

Introducing ExpectThat: A CoffeeScript Assertion Library

I'm a big fan of automated testing. In fact, on the rare occasions that I don't write tests, I find that I can't shake the thought that something has been missed.

As with all aspects of my coding efforts, I am constantly looking for ways to improve the process, make tests more readable, and reduce room for error. With these goals in mind, I'd like to introduce ExpectThat.


What is ExpectThat?

ExpectThat is an expressive, self-documenting, assertion library for CoffeeScript, that seeks to improve testing efforts with your favorite testing framework. It does this by providing a syntax similar to FsUnit (a library for F#) that makes assertions more readable and then automatically translates that readable code into descriptive test output. This ensures that your test names always stay in sync with your tests and allows your code to speak for itself. ExpectThat currently supports Pavlov, QUnit, and Jasmine. Overtime, support for additional testing frameworks will be added.

Let's See it in Action

The following example shows how to write tests with ExpectThat for Pavlov in CoffeeScript:
pavlov.specify "Example Specifications", ->
    foo = "bar"
    describe "When testing 'should equal'", ->
        expectThat -> foo.should equal "bar"
    describe "When testing 'shouldnt equal'", ->
        expectThat -> foo.shouldnt equal "baz"
    describe "When testing for 'true'", ->
        expectThat -> (foo is "bar").should be true
        expectThat -> (foo is "baz").shouldnt be true
    describe "When testing for 'false'", ->
        expectThat -> (foo is "baz").should be false
        expectThat -> (foo is "bar").shouldnt be false
    describe "When testing 'greater than'", ->
        expectThat -> (9.1).should be greaterThan 9
        expectThat -> (9.1).shouldnt be greaterThan 10
        expectThat -> 10.shouldnt be greaterThan 10
Here's a screenshot of the result:
Other Testing Frameworks

As I mentioned, ExpectThat currently supports QUnit and Jasmine in addition to Pavlov. The following are examples for each of these.

QUnit:
module "Example QUnit Specifications"

foo = "bar"

module "When testing should equal"

expectThat -> foo.should equal "bar"

module "When testing shouldnt equal"

expectThat -> foo.shouldnt equal "baz"

module "When testing for true"

expectThat -> (foo is "bar").should be true
expectThat -> (foo is "baz").shouldnt be true

module "When testing for false"

expectThat -> (foo is "baz").should be false
expectThat -> (foo is "bar").shouldnt be false
Jasmine:
describe "Example Jasmine Specifications", ->
    foo = "bar"
    describe "When testing should equal", ->
        expectThat -> foo.should equal "bar"
    describe "When testing shouldnt equal", ->
        expectThat -> foo.shouldnt equal "baz"
    describe "When testing for throw", ->
        expectThat -> (-> throw "test exception").should throwException
        expectThat -> (-> throw "test").should throwException "test"
    describe "When testing for less than", ->
        expectThat -> 10.should be lessThan 11
        expectThat -> (10.1).shouldnt be lessThan 10
Getting Started with ExpectThat

There are a couple of ways to get started with ExpectThat. First, head over to the ExpectThat GitHub site and browse through the documentation. You can then clone the repo and grab any of the examples from the example folder. If you are writing an ASP.NET app in Visual Studio, another option is to install one of the available NuGet packages.

Available Assertions

ExpectThat currently provides the following assertions:

- equal
- stictlyEqual
- false
- true
- greaterThan
- greaterThanOrEqual
- lessThan
- lessThanOrEqual
- throwException
- 'to' and 'be' can be used in most cases to make tests more readable.

In addition to the out-of-the-box assertions, ExpectThat allows for the creation of custom assertions. Examples of this for each of the supported testing frameworks are available in the example folder on GitHub.

ExpectThat in JavaScript

While the syntax of ExpectThat works best with CoffeeScript, you can certainly use it in JavaScript as well. Simply add in the missing braces, parens, semi-colons, function keywords, etc. The following provides a simple example for Pavlov:
pavlov.specify("expectThat Specifications", function() {
    describe("When testing should equal", function() {
        var foo = "bar";
        expectThat(function() {
            foo.should(equal("bar"));
        });
        expectThat(function() {
            (foo + "test").should(equal("bartest"));
        });
    });
});
Getting Involved

There are a lot of things left to do for ExpectThat and I'd love to hear your thoughts on direction, enhancements, etc. as well as have any help that anyone would like to offer. If you want to get involved, fork me on GitHub.



Sunday, December 25, 2011

Announcing FsUnit 1.0

A couple of weeks ago I announced a few enhancements to FsUnit. Today, I'm proud to announce the release of FsUnit 1.0. Version 1.0 includes support for additional testing frameworks, a new assertion function, and more...

New Testing Framework Support:

All previous releases of FsUnit provided support for only NUnit; however, the goal for FsUnit has always been to provide support for other major testing frameworks as well. This release largely accomplishes this goal by adding support for MbUnit version 3.3.454.0 and xUnit.NET version 1.8.0.1549. While the majority of functions provided for NUnit are also provided for these two testing frameworks, there are a couple of features that are not available. Each of these missing features can easily be worked around and the FsUnit unit tests provide examples of this.

NuGet Packages:

The easiest way to get started with FsUnit is to install one of the following NuGet packages.

- FsUnit for NUnit can be installed via the original NuGet package ID of FsUnit.
- FsUnit for xUnit.NET can be installed via the FsUnit.xUnit package ID.
- FsUnit for MbUnit can be installed via the FsUnit.MbUnit package ID.
Additional Assertion:

In addition to support for MbUnit and xUnit.NET, the equalWithin function has been added. Thanks to erdoll for requesting this enhancement and for providing much of the code for the NUnit implementation. The equalWithin function allows an equality assertion with a specified tolerance. Examples are provided below:

NUnit Example:
module Test.``equalWithin assertions``

open NUnit.Framework
open FsUnit

[<Test>]
let ``should equal within tolerance when less than``() =
    10.09 |> should (equalWithin 0.1) 10.11

[<Test>]
let ``should not equal within tolerance``() =
    10.1 |> should not ((equalWithin 0.001) 10.11)
xUnit.NET Example:
module Test.``equalWithin assertions``

open Xunit
open FsUnit.Xunit

[<Fact>]
let ``should equal within tolerance when less than``() =
    10.09 |> should (equalWithin 0.1) 10.11

[<Fact>]
let ``should not equal within tolerance``() =
    10.1 |> should not ((equalWithin 0.001) 10.11)
MbUnit Example:
module Test.``equalWithin assertions``

open MbUnit.Framework
open FsUnit.MbUnit

[<Test>]
let ``should equal within tolerance when less than``() =
    10.09 |> should (equalWithin 0.1) 10.11

[<Test>]
let ``should not equal within tolerance``() =
    10.1 |> should not ((equalWithin 0.001) 10.11)
Now on GitHub:

Last but not least, an FsUnit GitHub site is now available at https://github.com/dmohl/FsUnit. FsUnit has had several contributors with submissions ranging from inception and NUnit implementation by Ray Vernagus, to major and minor enhancements, to examples and documentation. I hope that this move to GitHub will spur additional collaboration. The GitHub site will now act as the primary place for development and collaboration, while the CodePlex site will house major releases. We would love to have additional features and contributors, so jump on over and submit a pull request.

On to the Next One...

We are already working on the next release of FsUnit. Rodrigo Vidal has submitted a few new NUnit assertions--which will be ported to the MbUnit and xUnit.NET implementations where possible. Additionally, there have been discussions of pulling in Phillip Trelford's F# friendly Mocking library

Where would you like to see FsUnit go? We'd love to hear from you!

Saturday, December 10, 2011

Porting Bryan's Erlang Function to F#

A week or two ago, Fresh Brewed Coder Bryan Hunter posted a video to explain how to debug Erlang apps. In the tutorial, he stepped through a recursive function to display the various concepts. I thought it would be interesting to take that simple example and explore a few ways to write it in F#. Let's start by reviewing Bryan's example (which calculates the average of a provided list of number).

Here's what his average.erl source file looks like:
-module(average).

-export([calculate/1]).

calculate(X) ->
     calculate(X,0,0).

calculate([H|T], Length, Sum) ->
     calculate(T, Length+1, Sum+H);

calculate([], Length, Sum) ->
     Sum/Length.
Porting the Code to F#:

So how would you write this in F#? As with any language, there are several options. A fairly straight forward port might look like this:
let calculate x =
    let rec calc list length sum =
        match list with
        | head :: tail -> calc tail (length+1) (sum+head)
        | [] -> sum/length
    calc x 0 0
printfn "Value is %O" (calculate [10;22])
Breaking it Down:

The above code defines the calculate function that takes a list of integers as a single argument.

Next, a recursive function (the "rec" keyword indicates that it is recursive) named calc is defined (line 2). This function takes a list of integers as the first argument, the current length as the second argument, and the current sum as the last argument.

At the heart of this recursive function is a pattern match against the provided list (line 3). Using something known as the cons pattern, the first pattern (line 4) attempts to decompose the provided list into a "head" (the first element in the list) and "tail" (the rest of the elements).

If the first pattern is a match, the calc function is called with the "tail" list as the first argument, the length value incremented by 1 as the second argument, and the result of the sum value combined with the first value from the list (i.e. the head) as the third argument. This continues until the list is empty, at which point the cons pattern no longer results in a match and the second pattern is evaluated.

By the time the second pattern (line 5) is evaluated, the match will succeed due to the list now being empty. This causes the average to be calculated (i.e. sum/length) and returned.

Line 6 kicks off the initial call to the calc recursive function with the initial list as the first argument and default length and sum values of 0.

Finally, the last line (line 7) kicks off the whole thing with the call to calculate the average of the numbers 10 and 22 (as used in Bryan's demo).

Another Approach:

While  the approach above is pretty compact, F# provides a library that contains a high-order function that makes this even easier. The following line of code will also calculate the average of the values in a list of integers:
[10;22] |> List.averageBy (fun number -> float number)

Thursday, December 1, 2011

Enhancements to FsUnit (version 0.9.1.1)

A new version (0.9.1.1) of FsUnit -- a DSL for writing unit tests in F# -- is now available on the NuGet gallery.

This version includes the following improvements:

 - Libraries for frameworks 3.5 and 4.0.
 - Support for NUnit version 2.5.10.11092.
 - Several new functions including: greaterThan, greaterThanOrEqualTo, lessThan, lessThanOrEqualTo, shouldFail, endWith, startWith, and ofExactType.

Examples of the functions mentioned above are shown below:
module FsUnit.``Given a bunch of random tests``

open NUnit.Framework
open FsUnit

[<Test>]
let ``When 11 it should be greater than 10``() =
    11 |> should be (greaterThan 10)

[<Test>]
let ``When 11 it should be greater than or equal to 10``() =
    11 |> should be (greaterThanOrEqualTo 10)

[<Test>]
let ``When 10 it should be less than 11``() =
    10 |> should be (lessThan 11)

[<Test>]
let ``When 10 it should be less than or equal to 11``() =
    10 |> should be (lessThanOrEqualTo 11)

[<Test>]
let ``When an empty List it should fail to contain item``() =
    shouldFail (fun () -> [] |> should contain 1)

[<Test>]
let ``When fsharp it should end with rp``() =
    "fsharp" |> should endWith "rp"

[<Test>]
let ``When fsharp it should start with fs``() =
    "fsharp" |> should startWith "fs"

[<Test>]
let ``When 1 it should be of exact type int``() =
    1 |> should be ofExactType<int>

An example of what this looks like when run in Resharper's Test Runner is shown below:


A Side Note: If you haven't written many tests in F#, the lack of spaces in the test names may surprise you. This is a feature of F# that allows almost any sequence of characters to be enclosed in double-backtick characters (i.e. ``) and consequently treated as an identifier.

I hope you enjoy the latest enhancements to FsUnit. You can find the full source at http://fsunit.codeplex.com/.

Building an ASP.NET MVC 4 Solution with F# and C#

There is a new project template available on Visual Studio Gallery for creating ASP.NET MVC 4 solutions with F# and C#. The current release of this project template allows creation of an empty ASP.NET MVC 4 web application (either ASPX or Razor), a F# project for controllers/models/etc., and an optional F# project that can be used to contain unit tests. The project creation wizard dialog box is shown below:



In the future, this template will be extended to include at least one additional project type.

To get the template, do the following (Note: Visual Studio 2010/11 Professional (or above) is required to use this template.):

1. In Visual Studio, navigate to File | New and select Online Templates.

2. Search for "fsharp mvc" and select the F# C# MVC 4 project template (see below):


The solution that was used to build this template can be found at https://github.com/dmohl/FsCsMvc4Template.