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.

Saturday, November 12, 2011

F# Silverlight Library Template in Visual Studio 11

If you have played with Visual Studio 11 much, you may have noticed that there isn't a F# Silverlight Library template out-of-the-box. This is presumably due to the fact that the current release of Visual Studio 11 is just a developer preview and there doesn't appear to be a version of F# 3.0 for Silverlight just yet. However, this doesn't stop you from creating Silverlight projects that target F# 2.0 in Visual Studio 11. In order to help you do this, I've created a project template that allows you to create a F# 2.0 Silverlight Library in Visual Studio 11. You can download the VSIX from here.

The following prerequisites exist for using this library:

1. Download and install the VS2011 Preview with F# 3.0 (see http://blogs.msdn.com/b/fsharpteam/archive/2011/09/14/f-3-0-developer-preview-now-available.aspx for more information).

2. Download and install the Microsoft F#, April 2011 CTP from http://www.microsoft.com/download/en/details.aspx?id=11100


Wednesday, November 9, 2011

New F# Windows Phone Library Project Template

There is a new F# Windows Phone Library project template now available on Visual Studio Gallery. This project template allows you to add a new F# library project to a Windows Phone solution rather than having to start with one of the solution templates that is initialized with both a C# and F# project.

As an example, you could easily build the F# and C# Win Phone App (Silverlight) solution by doing the following:

1. Create a new C# Windows Phone Application (Silverlight).
2. Add a new F# Windows Phone Library project to the solution.
3. Add a new XML file to the F# project named MainPage.xaml.
4. Add content to the MainPage.xaml file as shown here (also change the Build Action option to Resource and the Copy to Output Directory option to Copy always).
5. Add the code from here to the File1.fs file.
6. Delete the MainPage.xaml and associated code-behind file from the C# project.
7. Change the App.xaml.cs code in the C# project to what is shown here (Note: You'll likely need to change the namespace).
8. Change the App.xaml code in the C# project to what is shown here (Note: You'll likely need to change the namespace).
9. Edit the properties of the C# project and change the Startup object drop down to the *.AppHost object.
10. Edit the WMAppManifest.xml file and change:


<DefaultTask  Name ="_default" NavigationPage="MainPage.xaml"/>

to 

<DefaultTask  Name ="_default"/>

11. Finally, add a reference to the F# project, build, and test.

Monday, November 7, 2011

A Coder Interview with Dan Mohl

A Coder Interview With Dan Mohl by Terrence Dorsey (@tpdorsey) was recently published in the articles section of The Code Project site. In it, I talk about tools, technology, and frameworks that interest me (F#, CoffeeScript, Node.js, etc.), my background, how the community has influenced my coding, and much more.

You can find the article at http://www.codeproject.com/KB/interviews/Interview-Dan-Mohl.aspx.

Sunday, October 30, 2011

Calling F# Libraries from Metro Style Apps

This weekend, I finally got around to trying to build a polyglot Metro style app (C# front-end + F# back-end). This post will talk about the project file changes that were required and the one outstanding issue that I'm still working. Additionally, a VSIX package is provided that provides the F# Metro Library project template as it exists today.

Note: This approach has only been tested with the simplest of examples.

Getting Setup:

1. In order to create a Metro style app, you need to install Windows 8 Developer Preview with Developer Tools.
2. To also have F#, you'll then need to install Visual Studio 11 Developer Preview.
3. Now create a new C# Windows Metro style application (I chose the Application template).

Adding F#:

If you have installed the VSIX that is linked at the bottom of this post, you can simply add the F# Metro Library, write some code, wire it up, and test. If not, you'll need to add a standard F# Library project and modify the project file.

Modifying the F# Project File:

To allow a F# Library project to be called from a Metro app., the project file must be modified so that it imports the Microsoft.Windows.UI.Xaml.Common.targets. While this small adjustment allows the project to be interacted with, the reference shown in the Metro style project will provide a warning indicating that something isn't quite copacetic. This warning can be eliminated by adding the following elements to the property group:

<TargetFrameworkIdentifier>.NETCore</TargetFrameworkIdentifier><TargetFrameworkVersion>v4.5</TargetFrameworkVersion>

Unfortunately, adding these elements causes some sort of conflict with the F# targets, which I am still working to resolve. I have not yet run into an issue (other than the unsightly warning display) that is caused by leaving out these two elements, so for the moment only the common Xaml targets import has been added.   

Conclusion:

While there is still a lot of work to do, adding the import of the common Xaml targets to the F# project file will allow you to start using F# projects from Metro style apps (Note: In simple cases only--for now).  Once the remaining issues are identified and resolved, I'll add the F# Metro Library VSIX to Visual Studio Gallery. Until then, you can find the F# Metro Library VSIX (with the known issues) here.

Sunday, October 16, 2011

Two New F# 3.0 Type Provider Related NuGet Packages

There are two new NuGet packages available that can help you get started with authoring or consuming custom type providers. Both NuGet packages depend on the FSharpx.TypeProviders library that I wrote about in my last post and that Mauricio introduced in his most recent post.

FSharpx.TypeProviders.Sample:

The FSharpx.TypeProviders.Sample package provides an example of how to consume the custom type providers included in the FSharpx.TypeProviders library. The package adds a Test.config file as well as a F# source file that contains example code for using the TypedAppSettings type provider.

FSharpx.TypeProviders.DslSample:

The FSharpx.TypeProviders.DslSample package makes it easy to quickly get started with authoring a custom type provider. The package adds a F# source file that contains the source for a very simple custom type provider, a F# script file that can be used to test the custom type provider, and a batch file that makes it easy to do manual test/debug activities.

You may be curious about the commands in the batch file and why they are needed. Section 5.6 of the document on Writing F# 3.0 Type Providers that was provided by the F# team on 09/24/2011 includes development tips that make this more clear:

5.6.1 Run Two Visual Studio Instances. You can use one Visual Studio to develop the type provider. You can test it in another, since the test IDE will take a lock on the DLL preventing it being rebuilt. Thus, the second instance of Visual Studio must be closed while the provider is built in the first instance, and then reopened. 

5.6.2 Debug type providers by using invocations of fsc.exe. Type providers are invoked by 

- fsc.exe (The F# Command Line compiler)
- fsi.exe (The F# Interactive compiler)
- devenv.exe (Visual Studio)

Debugging type providers can often be easiest using fsc.exe on a test script file (e.g. script.fsx). This is because

- You can launch debug using a command-line prompt devenv /debugexe fsc.exe script.fsx - You can use print-to-stdout logging

I have tried both approaches and agree that the second is definitely the easiest. The .fsx and .bat files provided in this NuGet package make this approach even easier. Simply modify the code of the type provider, then test/debug by launching the batch file. Note: If/when changes to the Test.fsx file are required, it is recommended that these changes be made in an editor outside of Visual Studio.

Friday, October 7, 2011

Authoring Type Providers with the TypeProviderDSL from FSharpx

Several days ago, I submitted my AppSettings Type Provider to the FSharpx project. FSharpx is an open source library that adds a number of useful "functional constructs on top of the core F# library". I strongly encourage checking it out.

One of the many things in FSharpx that I find useful is the TypeProviderDSL. This is a DSL that sits on top of the ProvidedTypes module provided in the F# 3.0 Sample Pack. With this DSL and a few other helpers in FSharpx, the code from the AppSettings Type Provider that I showed in a previous post becomes easier to read. Plus, a few lines of code are shaved off in the process.

Let's look at a few of the features of the TypeProviderDSL that are used by the AppSettings Type Provider.

1. The erasedType function provides a simple way to create a ProvidedTypeDefinition.
2. The staticParameter function encapsulates the code needed to define a static parameter.
3. The literalField function makes it slightly easier to create a ProvidedLiteralField.
4. The addXmlDoc function provides a common way to add XML documentation.
5. Lastly, the |+> operator makes it very easy to add members.

Here's the end result:



You can get FSharpx.TypeProviders from the NuGet Gallery at http://www.nuget.org/List/Packages/FSharpx.TypeProviders and find the source on GitHub at https://github.com/fsharp/fsharpx/tree/TypeProviders.

Monday, October 3, 2011

MSDN Magazine Article: Authoring an F#/C# VSIX Project Template

My MSDN Magazine article entitled Authoring an F#/C# VSIX Project Template is now available in the October 2011 issue of MSDN Magazine.

A big thanks to Elijah Manor, Rick Minerich, and Chris Marinos for reviewing the article!

You can find the online version at http://msdn.microsoft.com/en-us/magazine/hh456399.aspx, the full code samples at http://fsharpmvc3vsix.codeplex.com/, and an enhanced version of the associated VSIX on Visual Studio Gallery at F#/C# ASP.NET MVC 3 Empty Web Application Template (see this previous post for more information about the extension that is available on Visual Studio Gallery).

Saturday, October 1, 2011

New F#/C# ASP.NET MVC 3 Template

There is a new F#/C# ASP.NET MVC 3 template now available on Visual Studio Gallery.


This template requires the ASP.NET MVC 3 Tools Refresh to be installed on the target machine and it provides functionality slightly similar to that which the Tools Refresh adds for C#/VB. Information on installing the ASP.NET MVC 3 Tools Refresh can be found at http://www.asp.net/mvc/mvc3.

With this project template, you will be able to create an empty ASP.NET MVC 3 Web Application. During the creation process, you will see a screen similar to the following with options that allow selection of ASPX or Razor view engine. Additionally, you can optionally choose to include a project which can be used to contain unit tests.


As usual, you can find the full source on my GitHub. Note: This template is an enhanced version of a template that is described in the MSDN Magazine article entitled "Authoring an F#/C# VSIX Project Template". I will be posting something about this article very soon.

Thursday, September 29, 2011

A Simple AppSettings Type Provider

With the F# 3.0 Developer Preview now available, I've been spending a decent chunk of my free time playing with Type Providers. With the announcement of the introductory guide and samples for authoring type providers I've had a hard time putting down the computer to sleep (let alone eat).

After a fair amount of experimentation, I've written my first type provider. It is admittedly quite simple and isn't production quality, but it has been a fun exercise. The basic idea is to read the appSettings elements from a config file, parse the values appropriately, and interact with them in a type safe way.

The sample config file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="test2" value="Some Test Value 5"/>
        <add key="TestInt" value="102"/>
        <add key="TestBool" value="True"/>
        <add key="TestDouble" value="10.01"/>
    </appSettings>
</configuration>
Here's the TypeProvider code:

Lastly, here's an example of how to use it.
#r "System"
#r @"bin\debug\AppSettingsTypeProvider.dll"

open System
open AppSettingsTypeProvider

type settings = AppSettings<"App.config">
printfn "Test2 String: %s" settings.test2 
printfn "Test Int: %i" settings.TestInt 
printfn "Test Bool: %b" settings.TestBool  
printfn "Test Double: %f" settings.TestDouble

Wednesday, September 21, 2011

Presentation: Dialing Up with F# and Windows Phone 7

A big thanks to Onorio for having me speak for the MIGang FSharp Special Interest Group tonight.

The slides that accompanied this presentation are shown below (use the mouse or the left and right arrow keys to navigate the slides):



Additionally, these slides and the associated examples can be found on my GitHub at https://github.com/dmohl/DialingUpWithFSharpAndWP7_Presentation.

Friday, September 16, 2011

F# Type Providers - Querying StackOverflow

If you haven't yet heard, the F# 3.0 preview bits were released to the wild a couple of days ago. Congrats to the F# team for this huge accomplishment!

One of the most anticipated features of F# 3.0 is Type Providers. Type Providers make F# the best available option for working in an information-rich world. Even though the preview has only been available for a few days, there is already quite a bit of content covering Type Providers. Here are a few examples:

http://msdn.microsoft.com/en-us/library/hh156509(v=VS.110).aspx
http://blogs.msdn.com/b/fsharpteam/archive/2011/09/14/f-3-0-developer-preview-now-available.aspx
http://fsharp3sample.codeplex.com/

Here's a simple example of querying the StackOverflow OData feed using a Type Provider:


How Do I Get It?

To start playing with F# 3.0, install the VS2011 dev preview and follow any of the step-by-step instructions provided at http://msdn.microsoft.com/en-us/library/hh156509(v=VS.110).aspx.

Tuesday, September 13, 2011

Advantages of CoffeeScript When Working with jQuery Templates

Working with jQuery Templates in CoffeeScript is very similar to working with them in JavaScript. However, there are a couple of CoffeeScript features that can make it even easier.

Here's a simple example (based on an example in the jQuery Template documentation):


As you can see, it's pretty similar to its JavaScript counterpart.

How can CoffeeScript make this better?

Enter Heredoc and String Interpolation...

Heredoc: Heredocs allow you to specify multi-line, formatted text. This can be useful when defining the template markup.

With heredocs, the markup from the previous example changes to this:


String Interpolation: CoffeeScript also provides Ruby style string interpolation. Here's an example of the markup after taking advantage of the string interpolation feature (Note: String interpolation only occurs within double-quoted strings and double-quoted heredocs):


Want to see it in action?

Go to http://tinkerbin.com/w0QoscT9, change the JavaScript Format drop down to CoffeeScript, then click the Run button.

Sunday, September 11, 2011

WP7 AccelerometerProxy in F#

With the release of the Windows Phone 7.1 SDK RC, there is now an easy way to use the emulator to simulate sensor data (such as data from the accelerometer). Unfortunately, I'm doing WP7 development in a VM and haven't yet had any luck getting the new SDK functionality to work in that environment.

I am however able to run the emulator using the WP7 Developer Tools RTW, but of course that version did not include functionality to simulate sensor data. There are a couple of options that people have identified for simulating accelerometer data (see Example using a mouse, Example using a Wiimote, Example using external app). For my needs, I decided to go with the mouse-driven approach.

While I could have easily used the C# library from the previously mentioned example, I decided instead to port that example to F#. The result is show here:


You can find the full example at https://github.com/dmohl/FsWP7Accelerometer.

Tuesday, September 6, 2011

Getting Started with the F# PowerPack - Part 4

In this series, I'm walking you through various features provided by the F# PowerPack.

Here are the links to the previous posts:

- Part 1
- Part 2
- Part 3

In this post, I'll briefly talk about Lexing, Parsing, SI (Metric) Units of Measure, Physical Constants, and Native Array.

Lexing and Parsing:

The FsLex and FsYacc documentation provides a good overview of how to get started with the lexing and parsing functionality offered by the PowerPack. As mentioned in this documentation, Jomo Fisher's Parsed Language Parser Template provides a great place to start from a code point of view. Note: Lexing and Parsing currently require the F# PowerPack to be installed with the MSI rather than with just the NuGet package.

SI (Metric) Units of Measurement:

Units of Measure are available in F# out-of-the-box (see http://cvslab.di.unipi.it/vslab/blog/post/2011/09/05/Ammeter-interface.aspx for a recent example of this feature in use); however, the PowerPack contains several useful predefined units of measure. Chris Smith speaks of the F# PowerPack in his Programming F# book and SI units of measure is one of the highlighted features. Additionally, Andrew Kennedy has a great post on this topic: http://blogs.msdn.com/b/andrewkennedy/archive/2008/09/02/units-of-measure-in-f-part-two-unit-conversions.aspx.

Here's a list of the SI Units that are provided:

Meter (m), Kilogram (kg), Second (s), Ampere (A), Kelvin (K), Mole (mol), Candela (cd), Hertz (Hz), Newton (N), Pascal (Pa), Joule (J), Watt (W), Coulomb (C), Volt (V), Farad (F), Ohm (ohm), Siemens (S), Weber (Wb), Tesla (T), Henry (H), Lumen (lm), Lux (lx), Becquerel (Bq), Gray (Gy), Sievert (Sv), Katal (kat)

PhysicalConstants:

The PowerPack also comes with a few useful predefined physical constants.

Here's the full list (note: these are basically straight from the code comments):

- Speed of light in vacuum
- Magnetic constant
- Electric constant
- Newtonian constant of gravitation
- Planck constant
- Dirac constant (a.k.a. the reduced Planck constant)
- Elementary charge
- Magnetic flux quantum h/2e
- Conductance quantum
- Electron mass
- Proton mass
- Fine-structure constant
- Rydberg constant
- Avogadro constant
- Faraday constant
- Molar gas constant
- Boltzmann constant R/N_A
- Stefan-Boltzmann constant
- Electron volt
- Unified atomic mass unit

NativeArray:

NativeArray.fs provides several modules and types that can be useful when doing native interop.

The NativeOps and Ref modules provide functions for pinning an object.

The types that are defined include PinnedArray, PinnedArray2, NativeArray, and FortranMatrix. There are a few examples of these types in use in the NativeArrayTests.fs file in the FSharp.PowerPack.Unittests project.

Thursday, September 1, 2011

Unit Testing a jQuery Plugin with CoffeeScript and Pavlov

If you search the web, you'll find a handful of good examples of jQuery plugins written in CoffeeScript, but there seems to be few examples of writing unit tests/specs in CoffeeScript. In this post, I'll show a very simple jQuery plugin with Pavlov specs.

Simple Plugin

This plugin simply wraps the jQuery UI dialog (http://jqueryui.com/demos/dialog/).
do ($ = jQuery) ->
  methods = 
    init: (options) ->
      dialogElement = $(options.dialogSelector)
      dialog = dialogElement.dialog autoOpen: false, modal: true, resizable: false 
      $(options.inputSelector).click -> dialog.dialog 'open'
  
  $.fn.simple = (options) -> 
    settings = dialogSelector:'.dialog', inputSelector:'.input'
    if options 
      $.extend settings, options
    methods.init settings
Pavlov Specs

QUnit is a JavaScript testing framework (learn more about it at http://docs.jquery.com/Qunit) and Pavlov (https://github.com/mmonteleone/pavlov) extends QUnit with several features that promote Behavior-Driven Development (BDD). Here's the example:
pavlov.specify "Simple Plugin", ->
  describe "Given default options", -> 
    before -> $(this).simple()
    describe "when executing a click event", ->
      before -> $('.input').click()
      it "it should open the dialog", ->
        assert($('.dialog').parents('.ui-dialog:visible').length).isTrue()
      after ->
        $('.dialog').dialog('close')
    describe "When the click event has not been executed", ->
      it "it should not have an open dialog", ->
        assert($('.dialog').parents('.ui-dialog:visible').length).isFalse()
      after -> 
        $('.dialog').dialog('close')

  describe "Given all custom options", -> 
    before -> 
      $(this).simple dialogSelector:'.customDialog', inputSelector:'.customInput' 
    describe "when executing a click event", ->
      before -> $('.customInput').click()
      it "it should open the custom dialog", ->
        assert($('.customDialog').parents('.ui-dialog:visible').length).isTrue()
      after ->
        $('.customDialog').dialog('close')

  describe "Given only a custom dialogSelector", -> 
    before -> $(this).simple dialogSelector:'.customDialog'
    describe "when executing a click event", ->
      before -> $('.input').click()
      it "it should open the custom dialog", ->
        assert($('.customDialog').parents('.ui-dialog:visible').length).isTrue()
      after ->
        $('.customDialog').dialog('close')

  describe "Given only a custom inputSelector", -> 
    before -> $(this).simple inputSelector:'.customInput' 
    describe "when executing a click event", ->
      before -> $('.customInput').click()
      it "it should open the dialog", ->
        assert($('.dialog').parents('.ui-dialog:visible').length).isTrue()
      after ->
        $('.dialog').dialog('close')
The Output

Once we have this in place and create a simple test runner page, we end up with the standard QUnit output that looks like the following:

Thursday, August 25, 2011

Adding NuGet Support to F# Interactive

A little over a week ago, Rick Minerich and I had a brief conversation about how cool it would be to install NuGet packages via the F# Interactive (FSI). After some research, there seems to be 3 options for accomplishing this:

1. Write a script that is loaded when the FSI starts.
2. Modify the source of FSI.exe (which can be found at http://fsharppowerpack.codeplex.com/).
3. Create an alternate F# Interactive Window VSIX that starts the FSI.exe as a new process as well as provides new commands.

In this post, I'll explore the first of these options.

Building the Script:

There are 3 steps to accomplishing the desired goal with option 1.

1. Create a F# script that has the ability to retrieve packages from NuGet and interact with Visual Studio. The script that I used to accomplish this can be found here.

Note: NuGet must be installed on the machine. Additionally, you will need to change the path to the NuGet.Core.dll reference if running a 32-bit version of Windows. This will be evident if you receive an error like the following when starting the F# Interactive Window - "error FS0084: Assembly reference 'C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies\NuGet.Core.dll' was not found or is invalid".

2. Update the FSI command line options in Visual Studio by going to Tools | Options | F# Tools | F# Interactive. Add "--use:<Path>\FsiExtension.fsx" to the "F# Interactive Options" value (see example below). Note: A full list of available FSI options can be found at http://msdn.microsoft.com/en-us/library/dd233172.aspx.


3. Open the F# Interactive Window (or reset the session if the window is already opened).

Taking it for a Test Drive:

Now that you are setup, it's time to try out the new functionality.

1. Create a new F# project and add a F# Script File (if one doesn't currently exist).

2.  Add some code (such as the following example from the Getting Started with F# PowerPack - Part 2 blog post) to the F# Script File:
open Microsoft.FSharp.Control  
  
let rec job = async {     
        for i in 1 .. 20 do    
            printfn "doing some work"  
            do! Async.Sleep 300  
            worker.ReportProgress i  
    }  
    and worker : AsyncWorker<_> = AsyncWorker(job)  
  
worker.ProgressChanged.Add(fun jobNumber -> printfn "job %d completed" jobNumber)   
worker.Error.Add(fun err -> printfn "Error: %A" err.Message)  
worker.Completed.Add(fun _ -> printfn "All jobs have completed")  
worker.Canceled.Add(fun _ -> printfn "Jobs have been canceled")  
  
worker.RunAsync() |> ignore  

3. In the F# Interactive Window, type InstallPackage "FSPowerPack.Core.Community";; and execute it. This will fire off the process to retrieve the FSPowerPack.Core.Community NuGet package from NuGet Gallery. The F# Interactive Window should look like the following once the process is complete:


This does two things:

1. It retrieves the specified NuGet package.
2. It adds any appropriate references to the fsx file. Your code will now look something like this:
#r @"C:\git\TestFsDte\packages\FSPowerPack.Core.Community.2.0.0.0\Lib\Net40\FSharp.PowerPack.dll"
open Microsoft.FSharp.Control  
  
let rec job = async {     
        for i in 1 .. 20 do    
            printfn "doing some work"  
            do! Async.Sleep 300  
            worker.ReportProgress i  
    }  
    and worker : AsyncWorker<_> = AsyncWorker(job)  
  
worker.ProgressChanged.Add(fun jobNumber -> printfn "job %d completed" jobNumber)   
worker.Error.Add(fun err -> printfn "Error: %A" err.Message)  
worker.Completed.Add(fun _ -> printfn "All jobs have completed")  
worker.Canceled.Add(fun _ -> printfn "Jobs have been canceled")  
  
worker.RunAsync() |> ignore  
4. You can also see what packages are installed by typing ShowInstalledPackages();;

Conclusion:

While this is hardly a perfect solution, hopefully it will at least spawn a few ideas. This implementation has several known issues (and probably several that are unknown). Let me know if you have ideas on better approaches or improvements.

Wednesday, August 24, 2011

Getting Started with the F# PowerPack - Part 3

In this series, I'm walking you through various features provided by the F# PowerPack.

Here are the links to the previous posts:

- Part 1
- Part 2

In this post, I'll discuss HashMultiMap and LazyList.

HashMultiMap:

http://cs.hubfs.net/forums/post/4371.aspx provides a nice description of the HashMultiMap type. Here's an excerpt from that link "HashSet and HashMultiMap are mutable structures, and both are implemented using hash comparison. When inserting a value, structural hash (or a user-supplied hash function) and (=) are used to find if a key already exists. Therefore, these are a good choice when the key is a complex or recursive data structure. HashSet contains keys only, and HashMultiMap contains keys and an associated value. Each key can only appear once in a HashSet or HashMultiMap, but multiple values can be bound to a single key in a HashMultiMap." Note: HashSet is now in System.Core. The version in the F# PowerPack has been deprecated.

Here is an example of HashMultiMap:
let hashSeq = 
    seq { for i in 1..100 do 
            yield ("key" + i.ToString()), ("value" + i.ToString())}
let hashMultiMap = HashMultiMap<string, string>(hashSeq, HashIdentity.Structural)
 
printfn "The value from the HashMultiMap for key:key5 is %s" (hashMultiMap.Item "key5")
LazyList:

Matthew Podwysocki has a nice post on Lazy Evaluation in F# that includes a section on LazyList. Here are a few excerpts from this post that explain the LazyList type. "The LazyList is a list which caches the results of the computed results on the items inside the collection." "The values aren't computed until the first is accessed, and then the results are cached."

The following contrived example shows the LazyList in use:
seq { for i in 1..10 do yield ("value" + i.ToString())}
|> LazyList.ofSeq
|> LazyList.iter(fun v -> printfn "The value from the LazyList is %s" v)
Wrapping Up:

That's it for today. You can find these examples (and several others) on my GitHub: https://github.com/dmohl/FSharpPowerPackExample.

Saturday, August 20, 2011

DevLink: Getting Started with F# Web Development

Thanks to all who attending the Getting Started with F# Web Development session at DevLink. The conference was excellent once again and I greatly enjoyed meeting each of you!

For those interested, the slides and code samples from this talk can be found at https://github.com/dmohl/GettingStartedWithWebDevInFSharpPresentation.

Thursday, August 18, 2011

Getting Started with the F# PowerPack - Part 2

In part 1 of this series, I provided a few links and examples of how to get started with the modules and types found in the math directory of the F# PowerPack. In this post, I'll do something similar with the command-line argument parser, AsyncOperations, AsyncStreamReader, and AsyncWorker.

ArgParser:

The F# PowerPack comes with a command-line parser that makes it easy to parse command-line options provided by a user.

The following links provide examples:

Example by Laurent Le Brun
Example by Robert Pickering
C# Port of Laurent Le Brun's Example by Steve Gilham

AsyncOperations:

Within the AsyncOperations.fsi file you'll find type extensions for StreamReader (AsyncReadToEnd) and File (AsyncOpenText, AsyncOpenRead, AsyncOpenWrite, AsyncAppendText, and AsyncOpen).

The following example is a modified version of one of the PowerPack unit tests, which shows AsyncOpenWrite and AsyncOpenRead in use.
open System.IO

async {
    async {
        let buffer = "F# is fun!"B
        use! is = File.AsyncOpenWrite "test.txt"
        do! is.AsyncWrite(buffer, 0, buffer.Length) 
        printfn "File written" } 
    |> Async.RunSynchronously

    async { 
        let buffer = Array.zeroCreate<byte>(7)
        use! is = File.AsyncOpenRead "test.txt"
        let! count = is.AsyncRead(buffer, 0, 7)
        printfn "File read"
        return count, buffer }
    |> Async.RunSynchronously |> ignore
} 
|> Async.Start

AsyncStreamReader:

The AsyncStreamReader type provides a simple approach to reading streams asynchronously. Here's an example:
open System
open System.IO
open System.Text

let text = [ new String([|for i in 1..1022 do yield 'x'|])
             new String([|for i in 1..1022 do yield 'y'|])
             new String([|for i in 1..1022 do yield 'z'|]) ].ToString()  

use stream = new MemoryStream()
stream.Write(Encoding.UTF8.GetBytes(text), 0, text.Length)
stream.Position <- 0L
let reader = new AsyncStreamReader(stream, Encoding.UTF8)          
async { let rec readAllChars () =
            async {
                let! eof = reader.EndOfStream
                if not eof then
                    let! character = reader.Read()
                    do printf "%s" (character.ToString())
                    return! readAllChars ()
                else 
                    printfn "%sRead complete" Environment.NewLine           
            }
        do! readAllChars ()
} 
|> Async.Start
Another example of AsyncStreamReader can be found here (see the answer provided by Brian McNamara).

AsyncWorker:

The AsyncWorker type provides a great way to define and launch a background worker. Don Syme shows how to create and use a similar type in his Async and Parallel Design Patterns in F#: Reporting Progress with Events (plus Twitter Sample) post.

Here's an example of the AsyncWorker type from the PowerPack.
open Microsoft.FSharp.Control

let rec job = async {   
        for i in 1 .. 20 do  
            printfn "doing some work"
            do! Async.Sleep 300
            worker.ReportProgress i
    }
    and worker : AsyncWorker<_> = AsyncWorker(job)

worker.ProgressChanged.Add(fun jobNumber -> printfn "job %d completed" jobNumber) 
worker.Error.Add(fun err -> printfn "Error: %A" err.Message)
worker.Completed.Add(fun _ -> printfn "All jobs have completed")
worker.Canceled.Add(fun _ -> printfn "Jobs have been canceled")

worker.RunAsync() |> ignore
Wrapping Up:

You can find working examples of each of these on my GitHub https://github.com/dmohl/FSharpPowerPackExample. Also, if you're interested in seeing more async examples, check out the series (C# Async Examples in F#) that Chris Marinos just started.

Sunday, August 14, 2011

Another CoffeeScript and jQuery UI Example

In a previous post, I showed a few examples of jQuery UI demos ported to CoffeeScript. While I prefer the approach that was shown in that post, there is another way that I could have done it. In this post, I'll show a different jQuery UI example (one of the the Slider demos) written using the CoffeeScript class structure.

You can find the full example (F# + ASP.NET MVC + CoffeeScript + jQuery UI) on my GitHub: https://github.com/dmohl/FsCoffeeScriptjQueryUIExample.
class Slider 
    constructor: ->
        $('#master').slider 
            value: 60 
            orientation: "horizontal" 
            range: "min" 
            animate: true

        $('#eq > span').each -> 
            value = parseInt $(this).text(), 10
            $(this).empty().slider
                value: value
                range: "min"
                animate: true
                orientation: "vertical" 

window.slider = new Slider()

Thursday, August 11, 2011

Getting Started with the F# PowerPack

I've been talking quite a bit about the F# PowerPack NuGet packages (see this post and this post for examples); however, I haven't written anything about the specific features that the F# PowerPack contains. To remedy this, I plan to do a series of posts to explore or review some of these features. The F# PowerPack has a wide variety of aspects, so if the features mentioned in this post are not of interest to you, don't let that stop you from reading future posts.

Note: The latest version of the F# PowerPack does not have official documentation. Documentation for version 1.9.6.16 can be found at http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/fsharp.powerpack/Microsoft.FSharp.Math.html.

I'll begin by looking at some of the modules and types found in the FSharp.PowerPack\math directory of the F# PowerPack source.

Associations:

The first module that we find in this directory is called GlobalAssociations. To quote from the comments in the F# PowerPack code, "Associations are a way of associating dictionaries of
operations with given types at runtime. Associations are global to a .NET application domain. Once specified an association may not be deleted or modified." The following links provide examples of this module in use:

F# INumerics Interface, and Matrix class by Yin
Example on StackOverflow by Tomas Petricek

Complex:

The module found in Complex.fs provides support for complex numbers and includes members that allow you to easily work with those numbers. A few of the members include retrieval of the real as well as imaginary parts of the complex number, addition/subtraction/multiplication of complex numbers, etc.

Here is a simple example from the F# PowerPack CodePlex home page:

let c = complex 0.0 1.0 * complex 0.0 1.0 // result is -1r+0i

Matrix:

There are several examples of using the Matrix type out on the web. The F# PowerPack CodePlex home page provides the following example:

let v  = vector [1.0;1.0;1.0] + vector [2.0;2.0;2.0] // result is (3.0; 3.0; 3.0)

Additionally, the previously mentioned post by Yin provides a few good examples. Also, Chapter 10 of the book Expert F# by Don Syme, Adam Granicz, and Antonio Cisternino has a section called Introducing Microsoft.FSharp.Math which contains a little more information and a few simple examples. A more involved example can be found here.

NativeArrayExtensionsForMatrix:

This module adds a few extension methods (i.e. of_vector, of_rowvec, and of_matrix) to the PinnedArray and PinnedArray2 types. An example of of_vector in use can be found here.

BigRational:

A simple example of the BigRational type in use, as documented on the F# PowerPack CodePlex home page, is shown below.

let r = (1N/2N) * (1N/3N) // result is 1/6

A more complex example can be found here.

Wrapping Up:

That's all for now. Everything described in this post (and the items described in the next few posts for this series) is provided in the FSharp.PowerPack.dll, which is available as part of an MSI on CodePlex as well as on NuGet Gallery as package ID FSPowerPack.Core.Community. In the next post for this series I will walk through and point out or provide examples for the command-line argument parser, AsyncOperations, AsyncStreamReader, and AsyncWorker.

Sunday, August 7, 2011

New F# PowerPack Packages on NuGet Gallery

There are several new F# PowerPack NuGet packages now available on NuGet Gallery. Additionally, the original F# PowerPack NuGet package has been modified slightly. A description of each PowerPack related package is provided below:

FSPowerPack.Community:


This is the original package. It includes all of the F# PowerPack libraries, but no longer includes the example .fs file. FSPowerPack.Community.Sample should be used when the example .fs file is desired.

FSPowerPack.Community.Sample:


This matches the contents of the original package (i.e. version 2.1.0.1 and below). It includes all F# PowerPack libraries as well as a simple .fs example file.

FSPowerPack.Core.Community:


This package contains only the FSharp.PowerPack.dll files for the various targeted frameworks.

FSPowerPack.Linq.Community:


This package contains the FSharp.PowerPack.Linq.dll files for the various targeted frameworks. It also takes a dependency on the FSPowerPack.Core.Community package.

FSPowerPack.Metadata.Community:


This package contains the FSharp.PowerPack.Metadata.dll files for the various targeted frameworks. It also takes a dependency on the FSPowerPack.Core.Community package.

FSPowerPack.Parallel.Seq.Community:


This package contains the FSharp.PowerPack.Parallel.Seq.dll files. It also takes a dependency on the FSPowerPack.Core.Community package.

Sunday, July 31, 2011

jQuery UI Examples in CoffeeScript

Recently, I've been playing with CoffeeScript and have found it to be a lot of fun. I'm a big fan of JavaScript and CoffeeScript has only added to the enjoyment of writing client-side code by taking away a few of the "bad parts" and reducing syntactic noise. To help learn the language, I took a few of the jQuery UI examples and re-wrote them in CoffeeScript. You can find the full solution (F# + ASP.NET MVC (Razor) + CoffeeScript) at https://github.com/dmohl/FsCoffeeScriptjQueryUIExample. (Note: You will need to install the Mindscape Web Workbench Visual Studio 2010 extension to make the CoffeeScript aspects work correctly. Visit this post by Scott Hanselman for information on getting started with this extension).

Here are the before and after examples:

This simple Portlets example comes from the jQuery UI demo found at http://jqueryui.com/demos/sortable/#portlets.

The JavaScript Version:

(function (portlets, undefined) {
    portlets.init = function() {
        $(".column").sortable({
            connectWith: ".column"
        });

        $(".portlet")
	        .addClass("ui-widget ui-widget-content ui-helper-clearfix ui-corner-all")
	        .find(".portlet-header").addClass("ui-widget-header ui-corner-all")
	        .prepend("<span class='ui-icon ui-icon-minusthick'></span>")
	        .end().find(".portlet-content");

        $(".portlet-header .ui-icon").click(function () {
            $(this).toggleClass("ui-icon-minusthick").toggleClass("ui-icon-plusthick");
            $(this).parents(".portlet:first").find(".portlet-content").toggle();
        });

        $(".column").disableSelection();
    };

} (window.portlets = window.portlets || {}));

The CoffeeScript Version:

((portlets) ->
  portlets.init = ->  
    $(".column").sortable(connectWith: ".column").disableSelection()

    $(".portlet")
      .addClass("ui-widget ui-widget-content ui-helper-clearfix ui-corner-all")
      .find(".portlet-header").addClass("ui-widget-header ui-corner-all")
      .prepend("<span class='ui-icon ui-icon-minusthick'></span>")
      .end().find ".portlet-content"

    $(".portlet-header .ui-icon").click -> 
      $(this).toggleClass("ui-icon-minusthick").toggleClass "ui-icon-plusthick"
      $(this).parents(".portlet:first").find(".portlet-content").toggle()
) window.portlets = window.portlets or {}

This simple Photo Manager example comes from the jQuery UI demo found at  http://jqueryui.com/demos/droppable/#photo-manager.

The JavaScript Version:

(function (pictureManager, undefined) {
    pictureManager.init = function() {
        var $gallery = $("#gallery"),
		    $trash = $("#trash");

	    $( "li", $gallery ).draggable({
		    cancel: "a.ui-icon",
		    revert: "invalid", 
		    containment: $( "#demo-frame" ).length ? "#demo-frame" : "document", 
		    helper: "clone",
		    cursor: "move"
	    });

	    $trash.droppable({
		    accept: "#gallery > li",
		    activeClass: "ui-state-highlight",
		    drop: function( event, ui ) {
			    deleteImage( ui.draggable );
		    }
	    });

	    $gallery.droppable({
		    accept: "#trash li",
		    activeClass: "custom-state-active",
		    drop: function( event, ui ) {
			    recycleImage( ui.draggable );
		    }
	    });

        $("ul.gallery > li").click(function (event) {
            var $item = $(this), $target = $(event.target);
            if ($target.is("a.ui-icon-trash")) {
                deleteImage($item);
            } else if ($target.is("a.ui-icon-zoomin")) {
                viewLargerImage($target);
            } else if ($target.is("a.ui-icon-refresh")) {
                recycleImage($item);
            }
            return false;
        });

        var recycle_icon = "<a href='link/to/recycle/script/when/we/have/js/off' title='Recycle this image' class='ui-icon ui-icon-refresh'>Recycle image</a>";
        function deleteImage($item) {
            $item.fadeOut(function () {
                var $list = $("ul", $trash).length ?
				$("ul", $trash) :
				$("<ul class='gallery ui-helper-reset'/>").appendTo($trash);

                $item.find("a.ui-icon-trash").remove();
                $item.append(recycle_icon).appendTo($list).fadeIn(function () {
                    $item
					.animate({ width: "48px" })
					.find("img")
						.animate({ height: "36px" });
                });
            });
        }

        var trash_icon = "<a href='link/to/trash/script/when/we/have/js/off' title='Delete this image' class='ui-icon ui-icon-trash'>Delete image</a>";
        function recycleImage($item) {
            $item.fadeOut(function () {
                $item
				.find("a.ui-icon-refresh")
					.remove()
				.end()
				.css("width", "96px")
				.append(trash_icon)
				.find("img")
					.css("height", "72px")
				.end()
				.appendTo($gallery)
				.fadeIn();
            });
        }

        function viewLargerImage($link) {
            var src = $link.attr("href"),
			title = $link.siblings("img").attr("alt"),
			$modal = $("img[src$='" + src + "']");

            if ($modal.length) {
                $modal.dialog("open");
            } else {
                var img = $("<img alt='" + title + "' width='384' height='288' style='display: none; padding: 8px;' />")
				.attr("src", src).appendTo("body");
                setTimeout(function () {
                    img.dialog({
                        title: title,
                        width: 400,
                        modal: true
                    });
                }, 1);
            }
        }
    };
} (window.pictureManager = window.pictureManager || {}));

The CoffeeScript Version:

((pictureManager) ->
  pictureManager.init = ->
    $gallery = $("#gallery")
    $trash = $("#trash")
    recycle_icon = "<a href='link/to/recycle/script/when/we/have/js/off'  
                            title='Recycle this image' 
                            class='ui-icon ui-icon-refresh'>Recycle image</a>"
    trash_icon = "<a href='link/to/trash/script/when/we/have/js/off' 
                         title='Delete this image' 
                         class='ui-icon ui-icon-trash'>Delete image</a>"

    deleteImage = ($item) ->
      $item.fadeOut ->
        $list = if $("ul", $trash).length then $("ul", $trash) else $("<ul class='gallery ui-helper-reset'/>").appendTo $trash
        $item.find("a.ui-icon-trash").remove()
        $item.append(recycle_icon).appendTo($list).fadeIn ->
          $item.animate(width: "48px").find("img").animate height: "36px"

    recycleImage = ($item) ->
      $item.fadeOut ->
        $item.find("a.ui-icon-refresh").remove().end()
          .css("width", "96px").append(trash_icon).find("img")
          .css("height", "72px").end().appendTo($gallery).fadeIn()

    viewLargerImage = ($link) ->
      src = $link.attr "href"
      title = $link.siblings("img").attr "alt"
      $modal = $("img[src$='#{src}']")
      if $modal.length
        $modal.dialog "open"
      else
        img = $("<img alt='#{title}' width='384' height='288' 
               style='display: none; padding: 8px;' />")
               .attr("src", src).appendTo "body"
        setTimeout (->
          img.dialog 
            title: title
            width: 400
            modal: true
        ), 1

    $("li", $gallery).draggable 
      cancel: "a.ui-icon"
      revert: "invalid"
      containment: if $("#demo-frame").length then "#demo-frame" else "document"
      helper: "clone"
      cursor: "move"
    
    $trash.droppable 
      accept: "#gallery > li"
      activeClass: "ui-state-highlight"
      drop: (event, ui) ->
        deleteImage ui.draggable
    
    $gallery.droppable 
      accept: "#trash li"
      activeClass: "custom-state-active"
      drop: (event, ui) ->
        recycleImage ui.draggable
    
    $("ul.gallery > li").click (event) ->
      $item = $(this)
      $target = $(event.target)
      if $target.is "a.ui-icon-trash"
        deleteImage $item
      else if $target.is "a.ui-icon-zoomin"
        viewLargerImage $target
      else recycleImage $item  if $target.is "a.ui-icon-refresh"
      false    
) window.pictureManager = window.pictureManager or {}

This simple User Manager example comes from the jQuery UI demo found at  http://jqueryui.com/demos/dialog/#modal-form.

The JavaScript Version:

(function (userManager, undefined) {
    userManager.init = function () {
        $("#dialog:ui-dialog").dialog("destroy");

        var name = $("#name"),
			email = $("#email"),
			password = $("#password"),
			allFields = $([]).add(name).add(email).add(password),
			tips = $(".validateTips");

        function updateTips(t) {
            tips
				.text(t)
				.addClass("ui-state-highlight");
            setTimeout(function () {
                tips.removeClass("ui-state-highlight", 1500);
            }, 500);
        }

        function checkLength(o, n, min, max) {
            if (o.val().length > max || o.val().length < min) {
                o.addClass("ui-state-error");
                updateTips("Length of " + n + " must be between " +
					min + " and " + max + ".");
                return false;
            } else {
                return true;
            }
        }

        function checkRegexp(o, regexp, n) {
            if (!(regexp.test(o.val()))) {
                o.addClass("ui-state-error");
                updateTips(n);
                return false;
            } else {
                return true;
            }
        }

        $("#dialog-form").dialog({
            autoOpen: false,
            height: 300,
            width: 350,
            modal: true,
            buttons: {
                "Create an account": function () {
                    var bValid = true;
                    allFields.removeClass("ui-state-error");

                    bValid = bValid && checkLength(name, "username", 3, 16);
                    bValid = bValid && checkLength(email, "email", 6, 80);
                    bValid = bValid && checkLength(password, "password", 5, 16);

                    bValid = bValid && checkRegexp(name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter.");
                    bValid = bValid && checkRegexp(email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com");
                    bValid = bValid && checkRegexp(password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9");

                    if (bValid) {
                        $("#users tbody").append("<tr>" +
							"<td>" + name.val() + "</td>" +
							"<td>" + email.val() + "</td>" +
							"<td>" + password.val() + "</td>" +
						"</tr>");
                        $(this).dialog("close");
                    }
                },
                Cancel: function () {
                    $(this).dialog("close");
                }
            },
            close: function () {
                allFields.val("").removeClass("ui-state-error");
            }
        });

        $("#create-user")
			.button()
			.click(function () {
			    $("#dialog-form").dialog("open");
			});        
    };
} (window.userManager = window.userManager || {}));

The CoffeeScript Version:

((userManager) ->
  userManager.init = ->
    name = $("#name")
    email = $("#email")
    password = $("#password")
    allFields = $([]).add(name).add(email).add password
    tips = $(".validateTips")

    updateTips = (t) ->
      tips.text(t).addClass "ui-state-highlight"
      setTimeout (->
        tips.removeClass "ui-state-highlight", 1500
      ), 500

    checkLength = (o, n, min, max) ->
      if o.val().length > max or o.val().length < min
        o.addClass "ui-state-error"
        updateTips "Length of #{n} must be between #{min} and #{max}."
        false
      else true

    checkRegexp = (o, regexp, n) ->
      unless regexp.test o.val()
        o.addClass "ui-state-error"
        updateTips n
        false
      else true

    $("#dialog-form").dialog 
      autoOpen: false
      height: 300
      width: 350
      modal: true
      buttons: 
        "Create an account": ->
          bValid = true
          allFields.removeClass "ui-state-error"
          bValid = bValid and checkLength name, "username", 3, 16
          bValid = bValid and checkLength email, "email", 6, 80
          bValid = bValid and checkLength password, "password", 5, 16
          bValid = bValid and checkRegexp name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter."
          bValid = bValid and checkRegexp email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com"
          bValid = bValid and checkRegexp password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9"
          if bValid
            $("#users tbody").append "<tr>" + "<td>" + name.val() + "</td>" + "<td>" + email.val() + "</td>" + "<td>" + password.val() + "</td>" + "</tr>"
            $(this).dialog "close"
        
        Cancel: ->
          $(this).dialog "close"
      
      close: ->
        allFields.val("").removeClass "ui-state-error"
    
    $("#dialog:ui-dialog").dialog "destroy"

    $("#create-user").button().click ->
      $("#dialog-form").dialog "open"
) window.userManager = window.userManager or {}