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.

Tuesday, November 29, 2011

Getting Setup for JavaScript Testing with Pavlov

I've talked about testing CoffeeScript with Pavlov in a previous post. Today, I'm going to talk about a couple of ways to quickly get started with Pavlov--a BDD API that sits on top of QUnit--in an ASP.NET web app.

In the past, whenever I wanted to start creating Pavlov specs, I would go out to the Pavlov GitHub site, grab the appropriate files, and add them to my web app. While this process isn't all that time consuming, there is now a better way. Now I can simply install the Pavlov NuGet package using the NuGet Visual Studio Extension. This package adds a folder named Specs under the Scripts folder that includes a barebones html file and pavlov.js.

An example of what the file structure looks like after this package is installed is shown below:


If I prefer to have a simple example to start with, I can alternatively install the Pavlov.Sample package. This adds the same files as the Pavlov package, but also includes an example.specs.js file with the code from the example on the Pavlov GitHub site.

Lastly, I've been writing a fair amount of CoffeeScript lately, so I may prefer to have the sample specs written in CoffeeScript. All that is needed for this is to make sure that Mindscape Web WorkBench Visual Studio Extension is installed (this is a onetime install) and then install the Pavlov.Coffee NuGet package. The files are then added to the project including a example.specs.coffee file that looks like this:



Thursday, November 24, 2011

Building F# Solutions in Visual Studio 11

I love to learn about new technology, seek to continually improve, and always look for ways to make things easier. I then do all that I can to share the knowledge, code, and/or tools that help to achieve these goals. With these goals in mind, I've joined with several friends in the creation of a new blogging community named Fresh Brewed Code. I'd strongly recommend keeping a close eye on the other Fresh Brewed Coders, as they will be producing some awesome content. You can see the announcement at http://freshbrewedcode.com/blog/2011/11/23/welcome-to-fresh-brewed-code/.

One of the other ways that I have attempted to achieve the goals mentioned above is through the creation of a number of Visual Studio project and item templates. Over the last several days, there have been updates to almost all of these templates. In this post I'll describe the changes that have been made--most of which have been implemented to allow support for the Developer Preview of Visual Studio 11 and F# 3.0.

I'm sure that you have used Visual Studio Gallery by now, but just in case you haven't yet had the chance, see http://bloggemdano.blogspot.com/2010/08/f-templates-now-on-visual-studio.html for how to get started. A screenshot of the Online templates view from the Developer Preview of Visual Studio 11 is shown below:



ASP.NET MVC:

F# and C# ASP.NET MVC3 - This project template generates the standard ASP.NET MVC 3 template output with separate projects for the view (ASPX in a C# project) and controllers/models (in a F# project). The latest release (version 1.3) adds support for Visual Studio 11 and F# 3.0. You will need to install the ASP.NET MVC 3 Tools Update (see http://www.asp.net/mvc/mvc3 and make sure to download/install the correct version for Visual Studio 10 or Visual Studio 11) to use this template.

F# C# MVC 3  - This is a dynamic project template that generates an empty ASP.NET MVC 3 solution with separate projects for view (C# - either ASPX or Razor), core (F#), and an optional F# project for unit tests. The template is based on the MSDN Magazine article entitled "Authoring an F#/C# VSIX Project Template" which can be found at http://msdn.microsoft.com/en-us/magazine/hh456399.aspx. You will need to install the ASP.NET MVC 3 Tools Update (see http://www.asp.net/mvc/mvc3 and make sure to download/install the correct version for Visual Studio 10 or Visual Studio 11) to use this template. Version 1.1 adds support for Visual Studio 11 and F# 3.0.

WPF:

F# Windows App (WPF, MVVM) - This project template generates a F# WPF solution with logical separation between View, ViewModel, Model, and Repository. The latest release (version 1.8) resolves a few bugs and adds support for Visual Studio 11 and F# 3.0.

F# and C# Windows App (WPF, MVVM) - This is a project template that generates a WPF solution with separation between View (C#), ViewModel (F#), Model (F#), and Repository (F#). The latest release (version 1.7) resolves a few bugs and adds support for Visual Studio 11 and F# 3.0.  


Web Service:

F# and C# Web Service (ASP.NET, WSDL) - This is a project template that generates a Web Service (WSDL) solution with separate projects for web (C#), services (F#), and contracts (F#). The underlying technology is Windows Communication Foundation. Version 1.5 adds support for Visual Studio 11 and F# 3.0.

Silverlight:

F# C# Web App (Silverlight) - This project template generates a Silverlight solution with separate projects for View (C#) and Core (F#).  The Core project includes logical separation between ViewModel, Model, and RemoteFacade. You should install the Silverlight 4 developer tools and/or the Silverlight 5 developer tools plus the April 2011 F# CTP. Version 1.2 adds support for Visual Studio 11 and includes a template wizard dialog that allows selection of Silverlight version 4 or 5. The determination of whether to display the wizard dialog is triggered off of the installed F# Silverlight client version. It will only display if both 4 and 5 are installed. Note: There are not yet F# 3.0 Silverlight DLLs. Because of this, the current version only support F# 2.0.

F# Web Application (Silverlight) - This F# project template generates a Silverlight project with logical separation between View, ViewModel, Model, and RemoteFacade. You should install the Silverlight 4 developer tools and/or the Silverlight 5 developer tools plus the April 2011 F# CTP. Version 1.4 adds support for Visual Studio 11 and includes a dialog that allows selection of the desired Silverlight Version 4 or 5 (depending on installations). Note: There are not yet F# 3.0 Silverlight DLLs. Because of this, the current version only support F# 2.0.

F# Empty Web Application (Silverlight) - This project template is similar to the F# Web Application (Silverlight) template; however, it does not include all of the example code. You should install the Silverlight 4 developer tools and/or the Silverlight 5 developer tools plus the April 2011 F# CTP. Version 1.1 adds support for Visual Studio 11, removes the C# host application, adds support to generate an HTML test file, and provides functionality to select the desired Silverlight version 4 or 5 (depending on the installation). Note: There are not yet F# 3.0 Silverlight DLLs. Because of this, the current version only support F# 2.0.

F# 2.0 Silverlight Library (for Visual Studio 11) - This is a project template that generates a F# 2.0 Silverlight project. It targets Visual Studio 11 only and will only be needed temporarily. You can read more about this template at http://bloggemdano.blogspot.com/2011/11/f-silverlight-library-template-in.html. Note: There are not yet F# 3.0 Silverlight DLLs. Because of this, the current version only support F# 2.0.

XAML Item Templates:

F# XAML Item Templates - This Visual Studio Extension provides a number of item templates that make working with F# XAML based projects (i.e. the WPF, Silverlight, and/or Windows Phone 7 project templates) much easier. Without these item templates adding new XAML files to one of these projects is a bit of a pain. You have to create a text or xml file, change the extension to .xaml, manually add the default XAML code, and change the Build Action for the .xaml file to Resource. Version 1.1 adds item templates for Windows Phone 7 (I'll talk more about this in a future post) and adds support for Visual Studio 11.
 
Project Templates That Do Not Currently Support Visual Studio 11:

Since the Developer Preview of Visual Studio 11 does not currently support Windows Phone 7 development, the Windows Phone 7 templates (i.e. C# WP7 with Caliburn.Micro, F# and C# Win Phone App (Silverlight), F# and C# Win Phone List App (Silverlight), and F# and C# Win Phone Panorama) have not yet been updated to support Visual Studio 11. This will be added as soon as a release of Visual Studio 11 is provided that does include this support.

F# and C# Web App (ASP.NET, MVC 2) - There is not currently an ASP.NET MVC 2 install for Visual Studio 11 and I don't anticipate one to ever be provided. Because of this, I have not (and do not intend to) add support for Visual Studio 11 to this project template.

Tuesday, November 15, 2011

A Pinch of CoffeeScript Sugar - Part 1

In this series, I plan to point out and provide a few examples of some cool syntactic sugar provided by CoffeeScript. In this post, I'll talk about destructuring assignment and splats.

I've shown how to write a jQuery plugin in CoffeeScript in a previous post. In the following example, I take that simple jQuery plugin and add a little more sugar.

The above example is based on the recommendations defined in the jQuery Plugins/Authoring documentation. There are a couple of interesting aspects of this code.

Line 10 (i.e. [_, args...] = arguments) is using two cool CoffeeScript features. The first is something called destructuring assignment. This feature allows you to take data from arrays or objects and place that data into something more wieldy. In this case, we are taking the JavaScript arguments object, destructuring it, and assigning all of the arguments except the first one to an array named args. This eliminates the need for me to type Array.prototype.slice.call(arguments, 1). If I had not used a splat (i.e ...), this would have assigned only the second argument to args. Note: Destructuring assignment has been added to JavaScript 1.7.

The second thing of interest on this line (which I've already briefly mentioned) is the use of the splat. The splat allows you to easily work with anything that involves a variable number of arguments. Since line 10 potentially involves more than 2 passed arguments, this is a perfect place to use a splat. As I mentioned before, the use of the splat in this case will generate JavaScript to slice the arguments array i.e. Array.prototype.slice.call(arguments, 1).

Lines 11 and 13 also use a splat, but the reasoning behind its use on these lines is slightly different. While this is still related to a varying number of arguments, it has to do with the passing of those arguments to a function rather than retrieval of the additional argument values. The splat in this case will generate JavaScript that uses the Function.apply method.

A little bit of sugar can make things much sweeter (ug...that was bad). I hope you find this post helpful and that you find lots of uses for the described features.