Sunday, November 14, 2010

Side-by-Side Asynchronous Programming Example in F#, C#, and VB

I was pleased to hear the announcement at PDC2010 by Anders Hejlsberg that C# and VB will likely be following the lead of F# by including asynchronous programming support. As Don Syme states in his post on this topic "the proposed design of C# and VB asynchronous programming is pleasant and simple, and heavily inspired by the corresponding feature of F#". In this post I will provide a simple example in F#, C#, and VB. The provided example is based on an example from a post by Don entitled "Async and Parallel Design Patterns in F#: Parallelizing CPU and I/O Computations". This example is also very similar to those provided in a series of posts on this topic by Tomas Petricek. I strongly recommend reading Don's post as well as Tomas's series.

F#:
open System
open System.IO
open System.Net

let getHtml url printStrategy =
    async { let request =  WebRequest.Create(Uri url)
            use! response = request.AsyncGetResponse()
            use stream = response.GetResponseStream()
            use reader = new StreamReader(stream)
            let contents = reader.ReadToEnd()
            do printStrategy url contents
            return contents }
 
let sites = ["http://www.bing.com";
             "http://www.google.com";
             "http://www.yahoo.com";
             "http://msdn.microsoft.com/en-us/fsharp/default.aspx"]

let printStrategy url (contents:string) =  
    printfn "%s - HTML Length %d" url contents.Length

let sitesHtml = Async.Parallel [for site in sites -> getHtml site printStrategy]
                |> Async.RunSynchronously

do printfn "\r\nProcess Complete\r\nPress any key to continue"

do Console.ReadLine() |> ignore

C#:
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Linq;

namespace CSharpAsync
{
    class Program
    {
        static async Task<string> GetHtml(string url, 
            Action<string, string> printStrategy)
        {
            var request = WebRequest.Create(new Uri(url));
            using (var response = await request.GetResponseAsync())
            {
                using (var stream = response.GetResponseStream())
                {
                    using (var reader = new StreamReader(stream))
                    {
                        var contents = reader.ReadToEnd();
                        printStrategy.Invoke(url, contents);
                        return contents;
                    }
                }
            }        
        }

        static async Task ProcessSites(string[] sites, 
            Action<string, string> printStrategy)
        {
            var sitesHtml = 
                await TaskEx.WhenAll(
                    sites.Select(site => GetHtml(site, printStrategy)));
            Console.WriteLine("\r\nProcess Complete\r\nPress any key to continue");
        }

        static void Main(string[] args)
        {
            var sites = new[] { "http://www.bing.com",
                            "http://www.google.com",
                            "http://www.yahoo.com",
                            "http://msdn.microsoft.com/en-us/fsharp/default.aspx" };

            Action<string, string> printStrategy =
                (url, contents) =>
                    Console.WriteLine("{0} - HTML Length {1}", url, contents.Length);
            
            ProcessSites(sites, printStrategy).Wait();

            Console.ReadLine();
        }
    }
}

VB:
Imports System
Imports System.IO
Imports System.Net
Imports System.Threading.Tasks
Imports System.Linq

Module Module1

    Async Function GetHtml(ByVal url As String, ByVal printStrategy As Action(Of String, String)) As Task(Of String)
        Dim request = WebRequest.Create(New Uri(url))
        Using response = Await request.GetResponseAsync()
            Using stream = response.GetResponseStream()
                Using reader = New StreamReader(stream)
                    Dim contents = reader.ReadToEnd()
                    printStrategy.Invoke(url, contents)
                    Return contents
                End Using
            End Using
        End Using
    End Function

    Async Function ProcessSites(ByVal sites As String(), ByVal printStrategy As Action(Of String, String)) As Task
        Dim sitesHtml = _
            Await TaskEx.WhenAll(sites.Select(Function(site) GetHtml(site, printStrategy)))
        Console.WriteLine("{0}Process Complete{0}Press any key to continue", _
            Environment.NewLine)
    End Function

    Sub Main()
        Dim sites = New String() {"http://www.bing.com", _
                "http://www.google.com", _
                "http://www.yahoo.com", _
                "http://msdn.microsoft.com/en-us/fsharp/default.aspx"}

        Dim printStrategy As Action(Of String, String) = _
            Sub(url, contents) Console.WriteLine("{0} - HTML Length {1}", url, contents.Length)
        ProcessSites(sites, printStrategy).Wait()
        Console.ReadLine()
    End Sub

End Module


Thursday, October 21, 2010

Presentation: Getting Started with F# Web Development - Slides

Thanks to all who came out to the Nashville Web Dev user group meeting tonight. Here are the slides from the presentation.


Thursday, October 14, 2010

Speaking at the October Nashville Web Dev User Group Meeting

I will be speaking at the Nashville Web Dev Group next Thurs. (10/21/2010) at 6:30 PM.

Here is the description of the talk:

Many of the features provided by F# lend themselves well to web development. In this talk, we will quickly go over some of the basics of the F# language, then dive into four quick ways to get started developing web application in F#. By the end, we will have built an F# and C# Silverlight application, an F# only Silverlight application, an F# and C# ASP.NET MVC 2 web application, and a web application with a platform called WebSharper.


Tuesday, September 28, 2010

C# WP7 Panorama with Caliburn.Micro Template

In my last post, I announced a F# and C# WP7 Panorama with Caliburn.Micro template. That template generated some interest in having a similar C# only template. You can find the C# only version on Visual Studio Gallery or through the Online Templates feature of Visual Studio 2010.

Here are the steps:

1. Download and install the RTW release of the Windows Phone Developer Tools.
2. In Visual Studio 2010, navigate to File -> New and select Online Templates.
3. Search for "Daniel Mohl" or "C# WP7 with Caliburn.Micro":


The full source is available at http://github.com/dmohl/CSharpWP7PanoramaWithCaliburnMicro.

Sunday, September 26, 2010

F#, Caliburn.Micro, and a New WP7 Template

Ever since I first heard about Caliburn.Micro, I have wanted to build an F# template that used it. With
the new WP7 panorama C# template that was included in the RTW release of the Windows Phone Developer Tools, I found a good opportunity. 

For those who haven't heard, Caliburn.Micro is a lightweight, feature packed MVVM framework. Rob Eisenberg (@eisenbergeffect) has done a fantastic job in developing this framework which consists of a "~50k assembly that builds for WP7, SL4, and WPF4" (Caliburn.Micro Introduced). While the assembly is small, the feature set is impressively large. Features include: ActionMessages, action and binding conventions, event aggregator, view locator, bootstrapper, logging, and much more. There are also a handful of features specific to WP7, not the least of which is the handling of tombstoning. To put it simply, Caliburn.Micro helps you code the "right way" while making everything easier along the way.

You can find the new F# WP7 Panorama template on Visual Studio Gallery or through the Online Templates feature of Visual Studio 2010.
Here are the steps:
(Note: Visual Studio 2010 Professional (or above) is required to use these templates.)

1. Download and install the RTW release of the Windows Phone Developer Tools.
2. In Visual Studio 2010, navigate to File -> New and select Online Templates.
3. Search for "Daniel Mohl" or "F# and C# Win Phone Panorama":


As with all of the templates that have been announced on this blog, you can find the full source on github.

Sunday, September 19, 2010

Monday, September 6, 2010

Pure-F# Templates Now Support the Visual Studio 2010 Shell SKU

I've been meaning to write this post for a few weeks now. With the announcement of the F# 2.0 standalone tools update for Visual Studio 2010 Shell, I have updated the pure-F# templates to support the IntegratedShell SKU. This includes templates F# Windows App (WPF, MVVM) and F# Web Application (Silverlight). Note: The F# Web Application template includes a C# application for the purpose of providing a hosting example. This C# hosting application will not be created successfully when using only the F# 2.0 standalone tools with Visual Studio 2010 Shell. Since this is not essential for the development of the actual Silverlight application, I decided to include IntegratedShell SKU support for this template with this as a known limitation.


Thursday, August 19, 2010

F# Windows Phone 7 (Silverlight) Templates Now On Visual Studio Gallery

Over the last few days, I've been working to put together a few Visual Studio 2010 Online Templates to help kick start development of Windows Phone 7 (WP7) applications in F#. These templates are now available on Visual Studio Gallery.

Follow these steps to get started:
(Note: Visual Studio 2010 Professional (or above) is required to use these templates.)

1. Download and install the Windows Phone Developer Tools.

2. In Visual Studio 2010, navigate to File -> New and select Online Templates.

3. Search for "Daniel Mohl" or "F# and C# Win Phone" (a sample is below):


Note: The WP7 FSharp.Core.dll has been included as part of these templates. It is also part of the Microsoft F# August 2010 CTP.

As always, I'd love to hear your feedback on these templates as well as ideas for others that you would like to see.

Tuesday, August 10, 2010

A F# Silverlight Template

In my last post I pointed out that the five templates that have been previously announced on this blog are now available on Visual Studio Gallery.  In this post, the count is being raised to six.  Thanks to Don Syme and a few others, a new "all F#" Silverlight template has been packaged and placed on Visual Studio Gallery.

Here's a description of the template:

"This is a F# project template that generates a Silverlight solution with logical separation between View, ViewModel, Model, and RemoteFacade.  While the Silverlight application is built entirely in F#, a C# web application is included for the purpose of providing a hosting example. "

You can get this template by doing the following:

1. In Visual Studio 2010, go to File -> New and select Online Templates

2. Search for Daniel Mohl or "F# Web Application (Silverlight)".







Monday, August 2, 2010

F# Templates Now On Visual Studio Gallery

Update: The online templates announced on this post have been slightly modified in order to
provide better naming consistency.  The new names are as follows: F# and C# Web App (ASP.NET, MVC 2), F# and C# Web Service (ASP.NET, WSDL), F# and C# Windows App (WPF, MVVM), F# Windows App (WPF, MVVM), F# and C# Web Application (Silverlight).

As Don Syme mentioned in a recent blog post, I've been working to get the five F# templates that have been announced on this blog up on Visual Studio Gallery.  I'm happy to say that all are now available.

You can install these templates by doing the following:

1. In Visual Studio 2010, go to File -> New and select Online Templates

2. Search for Daniel Mohl or one of the following template names:
   - F# ASP.NET MVC 2 Web Application
   - F# Web Service (WSDL)
   - F# and C# WPF Application (MVVM)
   - F# WPF Application (WPF)
   - F# Silverlight Application (MVVM)

Here is an idea of what it will look like if you search the online templates in Visual Studio 2010 for Daniel Mohl:


Additionally, I strongly recommend that you check out the two templates created by Jomo Fisher.

- F# Parsed Language Starter  (additional information can be found here)
- F# ASP.NET OData Web Service (additional information can be found here)

I'd love to get your feedback on all of these templates.  Also, let me know if there are any additional F# templates that you would like to see.

Wednesday, July 28, 2010

An F# Silverlight MVVM Multi-Project Template

In the spirit of continuing to build up set of project templates for F#, I've created an F# Silverlight MVVM multi-project template.

Here are the links to the other templates that have been announced on this blog:

- WPF MVVM Multi-Project  Template: A Polyglot Approach
- An F# WPF MVVM Project Template
- Standard WCF Template 
- Standard ASP.NET MVC 2 Template

The code provided by this multi-project template creates an application that is very similar to the output of the previously metioned F# WPF templates.

It looks something like this:


The following list shows the high level code changes that were needed to port the polyglot WPF template to Silverlight:

- Created new projects from the default C# and F# Silverlight 4 project templates.
- Made several revisions related to XAML resources.
- Changed the DataGrid control and Label controls to the Silverlight versions.

You can download the template here and find the full source at http://github.com/dmohl/FSharpSilverlightMVVMTemplate.

Sunday, July 25, 2010

The Mars Rovers Challenge

The Mars Rovers Challenge is a simple software development exercise.

The details are as follows:

---------------------------------------------
A squad of robotic rovers are to be landed by NASA on a plateau on Mars.
This plateau, which is curiously rectangular, must be navigated by the
rovers so that their on-board cameras can get a complete view of the
surrounding terrain to send back to Earth.

A rover's position and location is represented by a combination of x and y
co-ordinates and a letter representing one of the four cardinal compass
points. The plateau is divided up into a grid to simplify navigation. An
example position might be 0, 0, N, which means the rover is in the bottom
left corner and facing North.

In order to control a rover, NASA sends a simple string of letters. The
possible letters are 'L', 'R' and 'M'. 'L' and 'R' makes the rover spin 90
degrees left or right respectively, without moving from its current spot.
'M' means move forward one grid point, and maintain the same heading.

Assume that the square directly North from (x, y) is (x, y+1).

INPUT:
The first line of input is the upper-right coordinates of the plateau, the
lower-left coordinates are assumed to be 0,0.

The rest of the input is information pertaining to the rovers that have
been deployed. Each rover has two lines of input. The first line gives the
rover's position, and the second line is a series of instructions telling
the rover how to explore the plateau.

The position is made up of two integers and a letter separated by spaces,
corresponding to the x and y co-ordinates and the rover's orientation.

Each rover will be finished sequentially, which means that the second rover
won't start to move until the first one has finished moving.

OUTPUT
The output for each rover should be its final co-ordinates and heading.

INPUT AND OUTPUT

Test Input:
5 5
1 2 N
LMLMLMLMM
3 3 E
MMRMMRMRRM

Expected Output:
1 3 N
5 1 E
---------------------------------------------

The solution that I have put together is admittedly way over-engineered and it doesn't cover every scenario (i.e. tracking of rovers, rover collisions, etc.).  However, it does satisfy the requirements defined above (and then some).  Additionally, it shows object-oriented design, DRY (Don't Repeat Yourself), application of many of the SOLID principles, and application of several design patterns (i.e. Command, Specification, Template, etc).

You can find the full solution at http://github.com/dmohl/CSharpMarsRoverChallenge.


Tuesday, July 20, 2010

Nashville Geek Lunch 11:30 AM Next Tuesday (7/27/2010)

It's time for another Nashville Geek Lunch. Head out to Qdoba in Brentwood, TN next Tuesday (7/27/2010) from 11:30 - 12:30 for good food and great conversation with some of Nashville's finest developers and technologists.  There is no set discussion topic; however, you'll undoubtedly hear a little about .NET 4, F#, jQuery, ASP.NET MVC, Ruby, and more.  Additional information can be found at http://www.nerddinner.com/2697.

I hope to see you there!

Monday, July 5, 2010

Presentation: 5 Best Practices for F# Development - Slides and Examples

Thanks to all who come out to the New England F# User Group meeting tonight!

Based on an excellent recommendation from Elijah Manor, I have embedded the slide deck in this post:
The slides and examples can also be found at http://github.com/dmohl/FSharpPresentationExamples.

Monday, June 28, 2010

WPF MVVM Multi-Project Template: A Polyglot Approach

In my last post, I provided a WPF MVVM multi-project template comprised entirely of F# projects.  While that approach is exciting, I found that having the Views in an F# project caused more pain than gain.  As an advocate for using the right tool for the job, I have created a new WPF MVVM multi-project template composed of an C# View project, an F# ViewModel project, and an F# Model project.  Additionally, this version includes an F# Repository project and an F# project called FSharpIoC that provides inversion of control functionality (this can easily be replaced with the IoC contrainer of your choice).

The F# code did not change significantly between this version and the last; however, the ExpenseItHomeViewModel.fs has been cleaned up due to refactoring and the introduction of the ExpenseReportRepository.

Here's the code:
namespace FSharpWpfMvvmTemplate.ViewModel

open System
open System.Windows
open System.Windows.Data
open System.Windows.Input
open System.ComponentModel
open System.Collections.ObjectModel
open FSharpWpfMvvmTemplate.Model
open FSharpWpfMvvmTemplate.Repository

type ExpenseItHomeViewModel(expenseReportRepository : ExpenseReportRepository)  =  
    inherit ViewModelBase()
    let mutable selectedExpenseReport = 
        {Name=""; Department=""; ExpenseLineItems = []}
    new () = ExpenseItHomeViewModel(
                  FSharpIoC.IoC.GetIoC.Resolve<ExpenseReportRepository>())
    member x.ExpenseReports = 
        new ObservableCollection<ExpenseReport>(
            expenseReportRepository.GetAllExpenseReports())
    member x.ApproveExpenseReportCommand = 
        new RelayCommand ((fun canExecute -> true), (fun action -> x.ApproveExpenseReport)) 
    member x.SelectedExpenseReport 
        with get () = selectedExpenseReport
        and set value = 
            selectedExpenseReport <- value
            x.OnPropertyChanged "SelectedExpenseReport"
    member x.ApproveExpenseReport = 
        MessageBox.Show(sprintf "Expense report approved for %s" x.SelectedExpenseReport.Name) |> ignore

You can find the template installer here and the full source at http://github.com/dmohl/PolyglotWpfMvvmTemplate.

Monday, June 21, 2010

An F# WPF MVVM Project Template

I've been planning for a while to create an F# WPF MVVM Template to add to the other templates that have been announced on this blog.  A resent post by Mark Pearl provided a great simple example which helped kick me into gear and bring this plan to fruition.

To get us up to date, here are the links to the other templates that I have created:

- Standard WCF Template
- Standard ASP.NET MVC 2 Template

This particular template is slightly different than the others.  While the others had most or all of the code written in F#, the views or endpoints were still provided via a C# project.  In contrast, this F# WPF MVVM template contains only F# projects.

What to Expect:

The code provided by this template creates an application that is loosely based on ExpenseIt (A simple expense report app. defined on this MSDN page). The following screenshot displays the produced application in action:


The Model:

The model for this application is comprised of two simple records:
type Expense =
    { ExpenseType : string
      ExpenseAmount : string}

type ExpenseReport =
    { Name : string
      Department : string
      ExpenseLineItems : seq<expense>}
The View Models:

The view models are fairly standard. Each view model inherits from a ViewModelBase class. The ExpenseItHomeViewModel class contains most of the code. Since these are the two most interesting classes associated with view models, they will be the only two shown.

ViewModelBase.fs
namespace FSharpWpfMvvmTemplate.ViewModel

open System
open System.Windows
open System.Windows.Input
open System.ComponentModel

type ViewModelBase() =
    let propertyChangedEvent = new DelegateEvent<PropertyChangedEventHandler>()
    interface INotifyPropertyChanged with
        [<CLIEvent>]
        member x.PropertyChanged = propertyChangedEvent.Publish
    member x.OnPropertyChanged propertyName = 
        propertyChangedEvent.Trigger([| x; new PropertyChangedEventArgs(propertyName) |])
ExpenseItHomeViewModel.fs
namespace FSharpWpfMvvmTemplate.ViewModel

open System
open System.Xml
open System.Windows
open System.Windows.Data
open System.Windows.Input
open System.ComponentModel
open System.Collections.ObjectModel
open FSharpWpfMvvmTemplate.Model

type ExpenseItHomeViewModel =   
    [<DefaultValue(false)>] val mutable _collectionView : ICollectionView
    [<DefaultValue(false)>] val mutable _expenseReports : ObservableCollection<ExpenseReport>
    new () as x = {_expenseReports = new ObservableCollection<ExpenseReport>(); 
                   _collectionView = null} then x.Initialize()
    inherit ViewModelBase
    member x.Initialize() =
        x._expenseReports <- x.BuildExpenseReports()
        x._collectionView <- CollectionViewSource.GetDefaultView(x._expenseReports)
        x._collectionView.CurrentChanged.AddHandler(
            new EventHandler(fun s e -> x.OnPropertyChanged "SelectedExpenseReport")) 
    member x.BuildExpenseReports() = 
        let collection = new ObservableCollection<ExpenseReport>()
        let mike = {Name="Mike" 
                    Department="Legal" 
                    ExpenseLineItems = 
                        [{ExpenseType="Lunch" 
                          ExpenseAmount="50"};
                        {ExpenseType="Transportation" 
                         ExpenseAmount="50"}]}
        collection.Add(mike)
        let lisa = {Name="Lisa"
                    Department="Marketing" 
                    ExpenseLineItems = 
                        [{ExpenseType="Document printing" 
                          ExpenseAmount="50"};
                        {ExpenseType="Gift" 
                         ExpenseAmount="125"}]}
        collection.Add(lisa)
        let john = {Name="John" 
                    Department="Engineering"
                    ExpenseLineItems = 
                        [{ExpenseType="Magazine subscription" 
                          ExpenseAmount="50"};
                        {ExpenseType="New machine" 
                         ExpenseAmount="600"};
                        {ExpenseType="Software" 
                         ExpenseAmount="500"}]}
        collection.Add(john)
        let mary = {Name="Mary"
                    Department="Finance"
                    ExpenseLineItems = 
                        [{ExpenseType="Dinner" 
                          ExpenseAmount="100"}]}
        collection.Add(mary)
        collection
    member x.ExpenseReports : ObservableCollection<ExpenseReport> = x._expenseReports
    member x.ApproveExpenseReportCommand = 
        new RelayCommand ((fun canExecute -> true), (fun action -> x.ApproveExpenseReport)) 
    member x.SelectedExpenseReport =
        x._collectionView.CurrentItem :?> ExpenseReport
    member x.ApproveExpenseReport = 
        MessageBox.Show(sprintf "Expense report approved for %s" x.SelectedExpenseReport.Name) |> ignore
The Views:

The views are similar to views used in any WPF MVVM application. The solution has three XAML files: ApplicationResources.xaml, MainWindow.xaml, and ExpenseItHome.xaml. Since ExpenseItHome.xaml is the most interesting of these three, it is provided below:
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase" 
      xmlns:ViewModel="clr-namespace:FSharpWpfMvvmTemplate.ViewModel;assembly=FSharpWpfMvvmTemplate.ViewModel" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" d:DesignWidth="424">
    <UserControl.DataContext>
        <ViewModel:ExpenseItHomeViewModel></ViewModel:ExpenseItHomeViewModel>
    </UserControl.DataContext>
    <UserControl.Resources>
        <ResourceDictionary Source="ApplicationResources.xaml" />
    </UserControl.Resources>
    <Grid Margin="10,0,10,10" VerticalAlignment="Stretch">

        <Grid.Resources>
            <!-- Name item template -->
            <DataTemplate x:Key="nameItemTemplate">
                <Label Content="{Binding Path=Name}"/>
            </DataTemplate>
            <!-- Expense Type template -->
            <DataTemplate x:Key="typeItemTemplate">
                <Label Content="{Binding Path=ExpenseType}"/>
            </DataTemplate>
            <!-- Amount item template -->
            <DataTemplate x:Key="amountItemTemplate">
                <Label Content="{Binding Path=ExpenseAmount}"/>
            </DataTemplate>

        </Grid.Resources>

        <Grid.Background>
            <ImageBrush ImageSource="watermark.png"  />
        </Grid.Background>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="auto"/>
        </Grid.RowDefinitions>
        <!-- People list -->
        <Label Grid.Row="0" Grid.ColumnSpan="2" Style="{StaticResource headerTextStyle}" >
            View Expense Report
        </Label>
        <Grid Margin="10" Grid.Column="0" Grid.Row="1" VerticalAlignment="Top">
            <Grid.RowDefinitions>
                <RowDefinition/>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>

            <Border Grid.Row="1" Style="{StaticResource listHeaderStyle}">
                <Label Style="{StaticResource listHeaderTextStyle}">Names</Label>
            </Border>

            <ListBox Name="peopleListBox" Grid.Row="2" 
                 ItemsSource="{Binding Path=ExpenseReports}"
                 ItemTemplate="{StaticResource nameItemTemplate}"
                 IsSynchronizedWithCurrentItem="True">
            </ListBox>

            <!-- View report button -->
        </Grid>
        <Grid Margin="10" Grid.Column="1" Grid.Row="1" DataContext="{Binding SelectedExpenseReport}" VerticalAlignment="Top">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="57*" />
                <ColumnDefinition Width="125*" />
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <!-- Name -->
            <StackPanel Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="0" Orientation="Horizontal">
                <Label Style="{StaticResource labelStyle}">Name:</Label>
                <Label Style="{StaticResource labelStyle}" Content="{Binding Path=Name}"></Label>
            </StackPanel>
            <!-- Department -->
            <StackPanel Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="1" Orientation="Horizontal">
                <Label Style="{StaticResource labelStyle}">Department:</Label>
                <Label Style="{StaticResource labelStyle}" Content="{Binding Path=Department}"></Label>
            </StackPanel>
            <Grid Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="2" VerticalAlignment="Top" HorizontalAlignment="Left">
                <!-- Expense type and Amount table -->
                <DataGrid ItemsSource="{Binding Path=ExpenseLineItems}" ColumnHeaderStyle="{StaticResource columnHeaderStyle}" AutoGenerateColumns="False" RowHeaderWidth="0" Margin="0,0,-139,0">
                    <DataGrid.Columns>
                        <DataGridTextColumn Header="ExpenseType" Binding="{Binding Path=ExpenseType}"  />
                        <DataGridTextColumn Header="Amount" Binding="{Binding Path=ExpenseAmount}" />
                    </DataGrid.Columns>
                </DataGrid>
            </Grid>
        </Grid>
        <Button Grid.Row="2" Command="{Binding ApproveExpenseReportCommand}" Style="{StaticResource buttonStyle}" Grid.Column="1" Margin="0,10,53,0">Approve</Button>
    </Grid>
</UserControl>
Conclusion:

You can download the template installer here and find the full source at http://github.com/dmohl/FSharpWpfMvvmTemplate.  I did run into a few limitations with having the views in an F# project.  Because of these limitations, I would likely use a polyglot approach with a C# project as the view container and F# projects for the model and view model containers for solutions that are any more complex than this example.  I plan to provide a template for the polyglot approach in my next blog post. 

Wednesday, June 16, 2010

Son of a Son of Obsidian (My Favorite VS2010 Theme)

A month or two ago I had a great time going through all of the Visual Studio themes that can be found out on http://studiostyles.info/. After trying several of them out, I landed on Son of Obsidian.  Here is an example of what this theme looks like when developing in F#:


While I really liked Son of Obsidian, there were a few settings that made my eyes hurt.  After tweaking font colors specific to Resharper, Visual Studio 2010 Productivity Power Tools, etc., I can now say that this is officially my favorite theme.

How Can I Get It?

A few people have asked how they can get this slightly modified version of Son of Obsidian.  This can be accomplished by doing the following:

1. Download Son of a Son of Obsidian here.
2. Open Visual Studio 2010.
3. Select "Tools" then "Import and Export Settings..." from the main menu.


4. In the resulting wizard, select "Import selected environment settings" and click "Next".
5. Select "No, just import new settings, overwriting my current settings" and click "Next".
6. Click the browse button, locate the file that you downloaded in step 1, and select it.  Then click "Next".
7. Click Finish.
8. Finally, assuming the import is successful, click "Close".

Sunday, June 13, 2010

The Standard WCF Service Application Template for F#

In the interest of building up a larger set of installed templates for F#, I've ported the standard C# WCF Service Application to F# and packaged it into a .vsi file.

Here are a few snippets from the solution that the template creates:

IService1.fs
namespace FSharpWcfServiceApplicationTemplate.Contracts

open System.Runtime.Serialization
open System.ServiceModel

[<ServiceContract>]
type IService1 =
    [<OperationContract>]
    abstract GetData: value:int -> string
    [<OperationContract>]
    abstract GetDataUsingDataContract: composite:CompositeType -> CompositeType
Service1.fs
namespace FSharpWcfServiceApplicationTemplate

open System
open FSharpWcfServiceApplicationTemplate.Contracts 

type Service1() =
    interface IService1 with
        member x.GetData value =
            sprintf "%A" value
        member x.GetDataUsingDataContract composite =
            match composite.BoolValue with
            | true -> composite.StringValue <- 
                          sprintf "%A%A" composite.StringValue "Suffix"
            | _ -> "do nothing" |> ignore
            composite
You can download the installer from here and get the full source from http://github.com/dmohl/FSharpWcfServiceApplicationExample.

Monday, June 7, 2010

FSharpCouch: A Simple CouchDB .NET API in F#


In one of my last posts I showed a simple web application (created with the help of WebSharper Platform 2010) that captured registration information from a user and saved it to a CouchDB database.  I've been using CouchDB for a while now and I'm still amazed at how quickly you can get things up and running when you don't have to worry about the object-relational impedance mismatch.

To interact with CouchDB, I primarily use Relax (a full featured ".NET API abstraction of CouchDB's (excellent) RESTful API"); however, I thought it might be fun and educational to create a simple CouchDB .NET API abstraction in F#.  Note: The code provided  here is loosely based on SharpCouch.

Just Show Me the Code:

Without any further ado, here's the code.
module FSharpCouch
    open System
    open System.Net
    open System.Text
    open System.IO
    open Newtonsoft.Json
    open Newtonsoft.Json.Linq

    let WriteRequest url methodName contentType content =
        let request = WebRequest.Create(string url)
        request.Method <- methodName
        request.ContentType <- contentType 
        let bytes = UTF8Encoding.UTF8.GetBytes(string content)
        use requestStream = request.GetRequestStream()
        requestStream.Write(bytes, 0, bytes.Length) 
        request
    let AsyncReadResponse (request:WebRequest) =
        async { use! response = request.AsyncGetResponse()
                use stream = response.GetResponseStream()
                use reader = new StreamReader(stream)
                let contents = reader.ReadToEnd()
                return contents }
    let ProcessRequest url methodName contentType content =
        match methodName with
        | "POST" -> 
            WriteRequest url methodName contentType content
        | _ -> 
            let req = WebRequest.Create(string url)
            req.Method <- methodName
            req
        |> AsyncReadResponse 
        |> Async.RunSynchronously
    let ToJson content =
        JsonConvert.SerializeObject content
    let FromJson<'a> json =
        JsonConvert.DeserializeObject<'a> json
    let BuildUrl (server:string) (database:string) =
        server + "/" + database.ToLower()
    let CreateDatabase server database =
        ProcessRequest (BuildUrl server database) "PUT" "" ""
    let DeleteDatabase server database =
        ProcessRequest (BuildUrl server database) "DELETE" "" ""
    let CreateDocument server database content = 
        content |> ToJson
        |> ProcessRequest (BuildUrl server database) "POST" "application/json"
    let GetDocument<'a> server database documentId =
        ProcessRequest ((BuildUrl server database) + "/" + documentId) "GET" "" ""
        |> FromJson<'a>
    let GetAllDocuments<'a> server database =
        let jsonObject = ProcessRequest ((BuildUrl server database) + "/_all_docs") "GET" "" ""
                         |> JObject.Parse
        Async.Parallel [for row in jsonObject.["rows"] -> 
                            async {return FromJson<'a>(row.ToString())}]
        |> Async.RunSynchronously
    let DeleteDocument server database documentId revision =         
        ProcessRequest ((BuildUrl server database) + "/" + documentId + "?rev=" + revision) "DELETE" "" ""
Conclusion:

F# + CouchDB = totally awesome! You can find the full solution with integration tests at http://github.com/dmohl/FSharpCouch.

Tuesday, June 1, 2010

F# Presentation for the New England F# User Group

I will be speaking at the New England F# User Group on July 5th, 2010 at 6:30 PM Eastern Time.  Here's the information:

Title: 5 Best Practices for F# Development

Abstract:

F# makes it very easy to develop high performance, readable, and efficient code. However, like all things, a lack of discipline and best practice adoption can lead to a mess. In this talk we will cover 5 best practices that you can start using today to make yourself a better F# developer. We will explore each best practice, discuss the reason(s) that the described approach is preferred, and explore a few examples.

For more information visit www.fsug.org.


Thursday, May 27, 2010

Getting Started with WebSharper Platform 2010

A little while ago a cool new product was brought to my attention that allows client-based web development in F#.  The name of this product is WebSharper Platform 2010.  In this post, I will show a simple example for getting started with WebSharper Platform 2010.

Overview of this Example: 
The following code is a slimmed down and slightly modified version of the example provided in the default WebSharper-1.0 template.  Additionally, this example saves the information captured on the form to a CouchDB database.  Note: To run this example, you will need to download and install the WebSharper Platform 2010 Standard - Version 1.0.28 - Public Release (Instructions can be found at http://www.intellifactory.com/products/wsp/GettingStarted.aspx).  Additionally, in order for the registration information to be saved to the CouchDB database, CouchDB must be running on the default port (5984) of the local machine and a database named registration must exist.

Setting up the Form:
Our basic form is setup with the help of the Formlets library ("a library for type-safe web form combinators" - http://www.intellifactory.com/docs/websharper.pdf). The JavaScript attribute informs the WebSharper compiler that the function should be translated from F# to JavaScript.
    [<JavaScript>]
    let RegistrationForm : Formlet<RegistrationInformation> =
        Formlet.Yield (fun firstName lastName email -> 
                           {FirstName = firstName; 
                            LastName = lastName; Email = email})
        <*> input "First Name" "Please enter your first name"
        <*> input "Last Name" "Please enter your last name"
        <*> inputEmail "Email" "Please enter a valid email address"
Creating the Form Validation:
You probably noticed the input and inputEmail function calls in the form setup. These functions create the form elements with appropriate validation.  The code is as follows:
    [<JavaScript>]
    let input (label: string) (error: string) = 
        Controls.Input ""
        |> Validator.IsNotEmpty error
        |> Enhance.WithValidationIcon
        |> Enhance.WithTextLabel label

    [<JavaScript>]
    let inputEmail (label: string) (error: string) = 
        Controls.Input ""
        |> Validator.IsEmail error
        |> Enhance.WithValidationIcon
        |> Enhance.WithTextLabel label
Adding the Flow:
In this simple example, the user completes the three fields and clicks submit. The information is then saved to couch and the user is redirected to a summary page. That sequence is setup with the following code:
    [<JavaScript>]
    let RegistrationSequence =
        let registrationForm =
            RegistrationForm
            |> Enhance.WithSubmitAndResetButtons
            |> Enhance.WithCustomFormContainer {
                Enhance.FormContainerConfiguration.Default with
                    Header = 
                        "Enter the following information to register:" 
                        |> Enhance.FormPart.Text 
                        |> Some
                }
        let completeRegistration registrationInformation () =
            SaveRegistrationToCouch registrationInformation
            FieldSet [
                Legend [Text "Registration summary"]
                P ["Hi " + registrationInformation.FirstName + " " + 
                    registrationInformation.LastName + "!" |> Text]
                P ["You are now registered." |> Text]]
        let flow =
            Flowlet.Do {
                let! initialForm = registrationForm
                return! Formlet.OfElement (completeRegistration initialForm)
            }
        Div [H1 [Text "Register today!"]] -< [flow.BuildForm()]

Saving the Information to CouchDB: 
The final piece of code that I will show from this example is the server side method that is called from the client to save the information to CouchDB. In the RegistrationSequence function, we saw a call to a function named SaveRegistrationToCouch. This function looks like this:
    [<Rpc>]
    let SaveRegistrationToCouch (registrationInformation:RegistrationInformation) =
        JsonConvert.SerializeObject registrationInformation
        |> FSharpCouch.CreateDocument couchDBUrl 
        |> ignore
As you can see, all it takes for us to expose a server-side method is to add the Rpc attribute to that function.

Viewing the Result:
The result is a nice little registration sequence that contains client-side validation.  An example of the initial form with all completed information is below:

Conclusion:
This example shows how easy it is to throw together a simple registration form with WebSharper Platform 2010. We've only touched the surface on the capabilities of this platform.  You can find out more by visiting the Intellifactory web site.  You can find the full solution at http://github.com/dmohl/WebSharper-Example.

Sunday, May 23, 2010

A Simple Inversion of Control (IoC) Container in F#

In this post I will show how to build a simple Inversion of Control (IoC) container in F#.  If you are new to IoC containers I would recommend getting acquainted by reading http://martinfowler.com/articles/injection.html and http://msdn.microsoft.com/en-us/library/aa973811.aspx.

The Code:
namespace FSharpIoC

open System
open System.Collections.Generic
open System.Reflection

module FSharpIoCModule = 
    let rec Resolve requestedType (typeContainer:Dictionary<Type,Type>) =
        let newType = typeContainer.[requestedType]
        let constructors = newType.GetConstructors() 
                           |> Array.sortBy (fun c -> c.GetParameters().Length) 
                           |> Array.rev
        let theConstructor = constructors.[0]
        match theConstructor.GetParameters() with
        | cstorParams when cstorParams.Length = 0 -> Activator.CreateInstance(newType)
        | cstorParams -> cstorParams 
                         |> Seq.map(fun (paramInfo:ParameterInfo) -> 
                                (Resolve paramInfo.ParameterType typeContainer)) 
                         |> Seq.toArray 
                         |> theConstructor.Invoke

type Container =
    val typeContainer : Dictionary<Type, Type>
    new () = {typeContainer = new Dictionary<Type, Type>()}
    member x.Register<'a,'b> () =        
        x.typeContainer.Add(typeof<'a>, typeof<'b>)
    member x.Resolve(requestedType) =
        FSharpIoCModule.Resolve requestedType x.typeContainer
    member x.Resolve<'a> () =
        FSharpIoCModule.Resolve typeof<'a> x.typeContainer :?> 'a
Using Our IoC Container From F#:

The code below is not exactly a "real world" example, but it does show how our IoC container could be used in an F# application:
module FSharpIoCExample

open System
open FSharpIoC

type Person =
    { FirstName : string
      LastName : string}

type IPersonFactory =
    abstract CreatePerson : unit -> Person

type PersonFactory() = 
    interface IPersonFactory with
        member x.CreatePerson () = 
            {FirstName = "TestFirst"; LastName = "TestLast"}

type PersonService = 
    val personFactory : IPersonFactory
    new (personFactory) = {personFactory = personFactory}
    member x.GetPerson () = 
        x.personFactory.CreatePerson()

let iocContainer = new Container()
do iocContainer.Register<IPersonFactory, PersonFactory>()
do iocContainer.Register<PersonService, PersonService>()
let personService = iocContainer.Resolve<PersonService>()
let person = personService.GetPerson()
do Console.WriteLine("The person's name is {0} {1}", person.FirstName, person.LastName)
do Console.ReadLine()
Using Our IoC Container From C#:

Here is the same example in C#:
using System;
using FSharpIoC;

namespace CSharpIoCExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var iocContainer = new Container();
            iocContainer.Register<IPersonFactory, PersonFactory>();
            iocContainer.Register<PersonService, PersonService>();
            var personService = iocContainer.Resolve<PersonService>();
            var person = personService.GetPerson();
            Console.WriteLine("The person's name is {0} {1}", person.FirstName, person.LastName);
            Console.ReadLine();
        }
    }

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    public interface IPersonFactory
    {
        Person CreatePerson();
    }

    public class PersonFactory : IPersonFactory
    {
        public Person CreatePerson()
        {
            return new Person { FirstName = "TestFirst", LastName = "TestLast" };
        }
    }

    public class PersonService
    {
        protected readonly IPersonFactory _personFactory;
        public PersonService(IPersonFactory personFactory)
        {
            _personFactory = personFactory;
        }

        public Person GetPerson()
        {
            return _personFactory.CreatePerson();
        }
    }
}
Conclusion

As you can see, it doesn't take much to build a slim featured IoC container in F#. You can find the full source at http://github.com/dmohl/FSharpIoC.

Thursday, May 20, 2010

Creating an F# Solution Template for Visual Studio 2010

The title of this post is misleading because you can't actually create a VS2010 solution template (to my knowledge at least).  However, you can create a multi-project template and when I first went looking for how to do this, a search for "how to create a VS2010 solution template" was the first thing that came to mind (apparently many others have done this as well).  Hopefully, this post will make it easier for others to find the information for which they are searching.

In my last post, I provided an F# ASP.NET MVC 2 Web Application template that provides the same functionality as the out of the box C# ASP.NET MVC 2 Web Application template.  In this post, I will show how that template was created.  The full solution including all *.vstemplate and *.vscontent files can be found at http://github.com/dmohl/FSharpMVC2Starter.

Creating the *.vstemplate File for Each Project:


The first step in creating a multi-project template is to create a *.vstemplate file for each of the projects that you wish to include.  This can be accomplished using the export template wizard in visual studio (view the steps on the MSDN web site) or by manually creating the template (view the steps on the MSDN website).

This is what my *.vstemplate file looks like for the FSharpMVC2.Controllers project:
<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Project">
  <TemplateData>
    <Name>FSharpMVC2.Controllers</Name>
    <Description>MVC Controllers in F#</Description>
    <ProjectType>FSharp</ProjectType>
    <ProjectSubType>
    </ProjectSubType>
    <SortOrder>1000</SortOrder>
    <CreateNewFolder>true</CreateNewFolder>
    <DefaultName>FSharpMVC2.Controllers</DefaultName>
    <ProvideDefaultName>true</ProvideDefaultName>
    <LocationField>Enabled</LocationField>
    <EnableLocationBrowseButton>true</EnableLocationBrowseButton>
    <Icon>__TemplateIcon.ico</Icon>
  </TemplateData>
  <TemplateContent>
    <Project TargetFileName="FSharpMVC2.Controllers.fsproj" File="FSharpMVC2.Controllers.fsproj" ReplaceParameters="true">
      <ProjectItem ReplaceParameters="false" TargetFileName="HomeController.fs">HomeController.fs</ProjectItem>
      <ProjectItem ReplaceParameters="false" TargetFileName="AccountController.fs">AccountController.fs</ProjectItem>
    </Project>
  </TemplateContent>
</VSTemplate>
The ProjectType element value of "FSharp" specifies that this is an F# template.

Creating the Root *.vstemplate File:

Once the *.vstemplate files have been created, it's time to create a root *.vstemplate.  This looks very similar to the project level *.vstemplate files; however, it references each project level *.vstemplate file rather than the specific project level source/content files.

My root level *.vstemplate file looks like this:
<VSTemplate Version="2.0.0" Type="ProjectGroup"
    xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">
    <TemplateData>
        <Name>F# ASP.NET MVC2 Web Application</Name>
        <Description>F# ASP.NET MVC2 Web Application</Description>
        <Icon>__TemplateIcon.ico</Icon>
        <ProjectType>FSharp</ProjectType>
    </TemplateData>
    <TemplateContent>
        <ProjectCollection>
            <ProjectTemplateLink ProjectName="FSharpMVC2.Controllers">
                src\FSharpMVC2.Controllers\MyTemplate.vstemplate
            </ProjectTemplateLink>
            <ProjectTemplateLink ProjectName="FSharpMVC2.Models">
                src\FSharpMVC2.Models\MyTemplate.vstemplate
            </ProjectTemplateLink>
            <ProjectTemplateLink ProjectName="FSharpMVC2.Core">
                src\FSharpMVC2.Core\MyTemplate.vstemplate
            </ProjectTemplateLink>
            <ProjectTemplateLink ProjectName="FSharpMVC2.Web">
                src\FSharpMVC2.Web\MyTemplate.vstemplate
            </ProjectTemplateLink>
        </ProjectCollection>
    </TemplateContent>
</VSTemplate>
Once again, the ProjectType element value of "FSharp" indicates that this is an F# template.

Compresssing the Files:

Once all of the *.vstemplate files are created, it is time to compress all files that are to be included in the template.  To do this, select all the desired items including the root *.vstemplate file, then right-click and choose Send To/Compressed (zipped) Folder.  This will create a single *.zip file.

Creating the Template Installer:

We are now ready to create our template installer.  This involves the creation of one last XML file named *.vscontent.  My FSharpMVC2Template.vscontent file looks like this:
<VSContent xmlns="http://schemas.microsoft.com/developer/vscontent/2005">
    <Content>
        <FileName>FSharpMVC2Template.zip</FileName>
        <DisplayName>F# ASP.NET MVC2 Web Application</DisplayName>
        <Description>F# ASP.NET MVC2 Web Application</Description>
        <FileContentType>VSTemplate</FileContentType>
        <ContentVersion>1.0</ContentVersion>
        <Attributes>
            <Attribute name="ProjectType" value="Visual Web Developer"/>
            <Attribute name="ProjectSubType" value=""/>
            <Attribute name="TemplateType" value="Project"/>
        </Attributes>
    </Content>
</VSContent>
Note: Make sure that the FileName element value matches the name of the compressed file that you made during the "Compressing the Files" step.

Once the *.vscontent file has been created, select it, and the previously created zip file, and compress them into a single zip file. Change the extension of this file to .vsi and you're ready for a test run.

Sunday, May 16, 2010

F# and the Standard ASP.NET MVC 2 Web Application Template

Tomas Petricek recently provided a great blog post on creating MVC web applications in F#.  I thought it might be nice to also have a template that replicates the functionality of the standard C# ASP.NET MVC 2 Web Application template. The primary aspects of this template that differ from Tomas's include custom validators, authentication and membership services, and several jQuery plugins that are recommended and frequently used by Elijah Manor.

Here are a few examples of some of the code differences.

Custom Validators:
namespace FSharpMVC2.Web.Models
open System
open System.ComponentModel.DataAnnotations
open System.ComponentModel
open System.Globalization
open System.Web.Security

[<AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)>]
[<Sealed>] 
type PropertiesMustMatchAttribute = 
    inherit ValidationAttribute 
        val typeId : obj
        val mutable originalProperty : string
        val mutable confirmProperty : string
        new (originalProperty, confirmProperty) = 
            {inherit ValidationAttribute("'{0}' and '{1}' do not match."); originalProperty = originalProperty; 
             confirmProperty = confirmProperty; typeId = new Object()} 
        member x.OriginalProperty with get() = x.originalProperty and set(value) = x.originalProperty <- value
        member x.ConfirmProperty with get() = x.confirmProperty and set(value) = x.confirmProperty <- value
        override x.TypeId with get() = x.typeId
        override x.FormatErrorMessage name =
            String.Format(CultureInfo.CurrentUICulture, x.ErrorMessageString, x.OriginalProperty, x.ConfirmProperty)
        override x.IsValid value =
            let properties = TypeDescriptor.GetProperties value
            let originalValue = properties.Find(x.OriginalProperty, true).GetValue(value)
            let confirmValue = properties.Find(x.ConfirmProperty, true).GetValue(value)
            Object.Equals(originalValue, confirmValue)

[<AttributeUsage(AttributeTargets.Field ||| AttributeTargets.Property, AllowMultiple = false, Inherited = true)>]
[<Sealed>] 
type ValidatePasswordLengthAttribute = 
    val minCharacters : int
    new () = {inherit ValidationAttribute("'{0}' must be at least {1} characters long."); 
                minCharacters = Membership.Provider.MinRequiredPasswordLength} 
    inherit ValidationAttribute 
        override x.FormatErrorMessage name =
            String.Format(CultureInfo.CurrentUICulture, x.ErrorMessageString, name, x.minCharacters)
        override x.IsValid value =
            let valueAsString = value :?> string
            (valueAsString <> null && valueAsString.Length >= x.minCharacters)
Authentication and Membership Services:
namespace FSharpMVC2.Web.Models

open System
open System.Web.Security

module InputValidation =
    let Validate stringValue errorMessage =
        match String.IsNullOrEmpty(stringValue) with
        | true -> failwith(errorMessage)
        | _ -> do "" |> ignore

type IMembershipService = interface
    abstract MinPasswordLength : int with get
    abstract ValidateUser : string*string -> bool
    abstract CreateUser : string*string*string -> MembershipCreateStatus
    abstract ChangePassword : string*string*string -> bool
end    

type AccountMembershipService =
    val provider : MembershipProvider
    new () = AccountMembershipService(Membership.Provider)
    new (provider) = {provider = provider}
    interface IMembershipService with 
        member x.MinPasswordLength with get() = x.provider.MinRequiredPasswordLength
        member x.ValidateUser (userName, password) =
            InputValidation.Validate userName "Username cannot be null or empty."
            InputValidation.Validate password "Password cannot be null or empty."
            x.provider.ValidateUser(userName, password)
        member x.CreateUser (userName, password, email) =
            InputValidation.Validate userName "Username cannot be null or empty."
            InputValidation.Validate password "Password cannot be null or empty."
            InputValidation.Validate email "Email cannot be null or empty."
            let (_, status) = x.provider.CreateUser(userName, password, email, null, null, true, null)
            status
        member x.ChangePassword(userName, oldPassword, newPassword) =
            InputValidation.Validate userName "Username cannot be null or empty."
            InputValidation.Validate oldPassword "OldPassword cannot be null or empty."
            InputValidation.Validate newPassword "NewPassword cannot be null or empty."            
            try
                let currentUser = x.provider.GetUser(userName, true)
                currentUser.ChangePassword(oldPassword, newPassword)
            with 
            | :? ArgumentException -> false
            | :? MembershipPasswordException -> false

type IFormsAuthenticationService =
    abstract SignIn : string*bool -> unit
    abstract SignOut : unit -> unit

type FormsAuthenticationService() =
    interface IFormsAuthenticationService with
        member x.SignIn(userName, createPersistentCookie) =
            InputValidation.Validate userName "Username cannot be null or empty"
            do FormsAuthentication.SetAuthCookie(userName, createPersistentCookie)
        member x.SignOut () =
            do FormsAuthentication.SignOut()
You can download the template installer by clicking here.  The full solution can be found at http://github.com/dmohl/FSharpMVC2Starter.  (Note: The full solution includes a few things that are not included in the template such as a sample test project for the home controller.)

Wednesday, May 5, 2010

Integrating F# and Erlang Using OTP.NET

Recently, I ran across a post that talked about a .NET library named OTP.NET.  OTP.NET is a port of a Java library named JInterface that allows a .NET application to act as an Erlang node.  OTP.NET hasn't been updated in a while and the API is a bit clunky, but the provided functionality is very cool.  Note: A forked version of OTP.NET that has been migrated to VS2010 can be found at http://github.com/dmohl/OTP.NET-2010.

I decided to give OTP.NET a test drive by adding a simple command-line interface to an Erlang project that I have been playing with called Querly.

Querly is a simple query engine that allows T-SQL style queries against a CouchDB database.  You can read more about Querly in the following posts:

- Querly - A Query Engine for CouchDB
- Setting Up Querly
- Getting Started with Querly: A Simple CouchDB Query Engine

Getting Setup


To make this work, we first need to do the following:

1. Setup Querly by following the instructions provided in the blog post entitled Setting Up Querly.
2. If you want to load up a database for testing, follow the instructions provided in the blog post entitled Getting Started with Querly: A Simple CouchDB Query Engine.
3. Make sure that RabbitMQ and CouchDB are running.
4. Launch Querly by navigating to the Querly directory and running a command such as:
"C:\Program Files\erl5.7.5\bin\werl.exe" -sname querly -setcookie supersecretcookie -pa ./ebin -pa ./src
5. Finally, in the Erlang interactive shell, run the following command:
querly:start().

If everything worked as expected, you should see something like this:

Building the F# Application

Now that we have the Erlang application up and running, it's time to put together the F# code that will allow us to join the Erlang node cluster and interact with Querly.  Note: You'll need to replace the value assigned to peerNode with the name of your querly node. The full solution can be found at http://github.com/dmohl/Ferly.
module Ferly

open System
open Otp

Console.Write ":>"  
let mutable input = Console.ReadLine()  

let erlangCookie = "supersecretcookie"
let peerNode = "querly@dmohl-PC" // Replace with querly node name

let connection =
    let cNode = new OtpSelf("querlyclientnode", erlangCookie)
    let sNode = new OtpPeer(peerNode)
    cNode.connect(sNode)

let RemoteCall (sql:string) = 
    let arguments = [|new Erlang.String(sql)|] : Erlang.Object[]
    do connection.sendRPC("querly_client", "sql_query", arguments) 
    connection.receiveRPC().ToString()

while input <> "quit" do 
    Console.Write(RemoteCall input)
    Console.Write "\n\n:>"   
    input <- Console.ReadLine()


We should now be able to run the F# application and write queries against a couch database.  An example of the running application after a few processed queries is shown below:


Wrapping Up


We have only touched the surface of the functionality provided by OTP.NET.  Hopefully this post has shown how OTP.NET can be used to quickly integrate F# with Erlang.  Unfortunately, there is not a lot of documentation out there for OTP.NET, so if you want to learn more, your best bet is to pull down the code and start thumbing through it.  Happy polyglot programming!


Sunday, May 2, 2010

Getting Started with Querly: A Simple CouchDB Query Engine

About a month ago, I introduced a simple project that allows limited T-SQL style queries against a CouchDB database.  The codename for that project is Querly.  Today, I'm going to talk a little about what you need to get started with Querly.

The other posts can be found in the following locations:

- Querly - A Query Engine for CouchDB  
- Setting Up Querly

Loading Up A Test Database

To get started with Querly, make sure that you have followed the instructions outlined in Setting Up Querly.  If all the tests run, you are ready to get started with Querly.  Press [Enter] to get back to the Erlang prompt.  In order to load up a database with several documents that we can play with, type  querly_load_tests:load_10000_people(). and press [Enter] (Note: This will take a little while to finish).

Writing Our First Query

Once the "person" database is loaded, we can start Querly and begin writing simple queries.

To start querly, type querly:start().

Here are a few samples of queries that can now be run (Note: The first query may take a few seconds as the documents are being loaded into an ETS table):

querly_client:sql_query("select * from person where Idno = 1").
querly_client:sql_query("select * from person where FirstName = TestFirst2").
querly_client:sql_query("select * from person where Dob= 08/28/1977 and FirstName = TestFirst3").

Querying Other Databases

In order to write T-SQL style queries against a database, a record must be defined in the src/record_definitions.hrl file.  An example for the person table is as follows:

-record(person, {'Idno', 'FirstName', 'LastName', 'Dob', 'Ssn'}). 
-define(personFields, record_info(fields, person)).

This definition makes it possible to use specific field names in the TSQL style queries.

Limitations

There are a number of known limitations in this simple query engine. 

The most notable limitations are as follows:

- The T-SQL style query functionality is limited to simple "where" clauses.  
- A record must be predefined in order to query a database.

Conclusion

Querly allows simple T-SQL style queries against a CouchDB database.  While Querly has a number of known limitations, it hopefully serves as a simple PoC and/or starting point for a CouchDB query engine.

Monday, April 26, 2010

A Distributed Hash Table (DHT) in F#: Recursion and Pattern Matching

This post is part of a series on the development of a distributed hash table (DHT) in F#.

You can find the previous posts at the following locations:
1. .NET Remoting in F#: A Start to a Distributed Hash Table
2. A Distributed Hash Table (DHT) in F#: Moving  from .NET Remoting to WCF
3. A Distributed Hash Table (DHT) in F#: Using Higher Order Functions for the Service Operation Calls

Joining the Node Cluster:

The simplest implementation defined in the Chord Protocol requires that each node only know about its successor node.  The circle of nodes, joined by each successor node association, makes up the node cluster. In order for a node to become part of the node cluster, it must execute a join request to any arbitrary node in the cluster.

The code that provides this functionality is provided below.  Note: The code base is getting too large to display in full.  The complete solution can be found at http://github.com/dmohl/Polyphony.

Part of ChordClient.fs
let rec FindSuccessorNode possiblePredecessorNode startingNode localNode (chordServerProxy:IChordServerProxy) =
    let valueOption = chordServerProxy.CallServer possiblePredecessorNode CommandType.Join [|localNode|]
    match valueOption with
    | Some value -> 
        let nodeNeighbors = value :?> NodeNeighbors
        match nodeNeighbors.PredecessorNode with
        | predecessorNode when possiblePredecessorNode = predecessorNode -> nodeNeighbors.SuccessorNode
        | _ when startingNode = nodeNeighbors.SuccessorNode -> 
            chordServerProxy.CallServer possiblePredecessorNode CommandType.UpdateSuccessorNode [|localNode|] |> ignore
            nodeNeighbors.SuccessorNode
        | _ when startingNode = "" ->
            FindSuccessorNode nodeNeighbors.SuccessorNode possiblePredecessorNode localNode chordServerProxy
        | _ -> FindSuccessorNode nodeNeighbors.SuccessorNode startingNode localNode chordServerProxy
    | None -> localNode

let JoinChordNodeNetwork localNode remoteNode (chordServerProxy:IChordServerProxy) =
    let successorNode = FindSuccessorNode remoteNode "" localNode chordServerProxy
    chordServerProxy.CallServer localNode 
        CommandType.UpdateSuccessorNode [|successorNode|] |> ignore
    successorNode    

Pattern Matching and Recursion:

Pattern matching and recursion are the two primary language features that are being used here.

Matt Podwysocki has a nice overview of pattern matching here.  Within that post he states:
"One of the interesting and more powerful features of the F# language is Pattern Matching.  Don't be tempted to think of them as simple switch statements as they are much more powerful than that.  Pattern matching is used to test whether the piece under test has a desired state, find relevant information, or substitute parts with other parts.  Most functional languages such as Haskell, ML, and OCaml have them, and F# is no exception to its support."  
Recursion and pattern matching often go hand in hand.  Recursion basically allows you to repeatedly call a function from within that same function.

In the code above, the function FindSuccessorNode is designated as a recursive function by the "rec" keyword.  A call is then made to a node to see if the two nodes should be associated.  The result of that call is then pattern matched against possible outcomes.  Depending on the match, the FindSuccessorNode is recursively called or the successor node is returned.


Part of ChordServer class in ChordServer.fs
        member x.RequestJoinChordNodeNetwork requestorNode =
            let result = 
                match requestorNode with
                | _ when requestorNode = x.node || x.node = x.successorNode ->
                    x.successorNode <- requestorNode 
                    BuildNodeNeighbors x.node x.node
                | _ when requestorNode > x.node && requestorNode < x.successorNode -> 
                    let requestorsSuccessor = x.successorNode 
                    x.successorNode <- requestorNode
                    BuildNodeNeighbors x.node requestorsSuccessor
                | _ -> 
                    BuildNodeNeighbors x.successorNode x.successorNode
            x.AddToFingerNodes requestorNode        
            result

Once again, pattern matching is the primary language feature being used.

Conclusion:

Pattern matching and recursion are two extremely powerful weapons in the functional programmer's arsenal. When combined, the possibilities are endless.

Sunday, April 18, 2010

Interacting with RabbitMQ via F# and Symbiote

Last week, I showed how easy it is to talk to CouchDB with F# and Symbiote.  In this post, I'll show how you can start interacting with RabbitMQ by adding an additional dozen or so lines of code.

RabbitMQ:
RabbitMQ is a complete and highly reliable enterprise messaging system based on the emerging AMQP standard. It is licensed under the open source Mozilla Public License and has a platform-neutral distribution, plus platform-specific packages and bundles for easy installation. (http://www.rabbitmq.com/)
Symbiote:

Symbiote is a set of libraries that reduce the radius of comprehension by providing simplified APIs "...to some of the better open source libraries available" as well as "...a way to centralize the configuration [and] dependency injection..." of said libraries (Robson, A., Symbiote).   

For those of you who haven't played with RabbitMQ and/or Symbiote, I strongly recommend checking them out!

Code:

Here's the code with the CouchDB interaction functionality as well as the RabbitMQ publish/subscribe functionality.

A couple of things to note about this sample:
1. CouchDB and RabbitMQ must be installed and running on the local machine.
2. Since Symbiote is under heavy development, the CouchDB related code has changed slightly from the example provided last week.
module Progam

open System
open Symbiote.Core
open Symbiote.Relax
open Symbiote.Daemon
open Symbiote.Jackalope
open Symbiote.Jackalope.Impl

type PersonCouchDocument =
    val id : string
    val mutable name : string
    val mutable address : string
    inherit DefaultCouchDocument 
        new (id, name, address) = 
            {id = id; name = name; address = address} then base.DocumentId <- id
        member x.Name
            with get () = x.name
        member x.Address
            with get () = x.address

type HandleMessage() =
    interface IMessageHandler<PersonCouchDocument> with
        member x.Process (message:PersonCouchDocument, messageDelivery:IMessageDelivery) =
            Console.WriteLine("Processing message for person {0}.", message.name)
            messageDelivery.Acknowledge()

type DemoService = 
    val couchServer : ICouchServer
    val bus : IBus
    new(couchServer, bus) as this = 
        {couchServer = couchServer; bus = bus} then this.Initialize()
    member public x.Initialize () =
        x.bus.AddEndPoint(fun x -> 
            x.Exchange("SymbioteDemo", ExchangeType.fanout).QueueName("SymbioteDemo")
                .Durable().PersistentDelivery() |> ignore)
    interface IDaemon with
        member x.Start () =
            do Console.WriteLine("The service has started")
            x.bus.Subscribe("SymbioteDemo", null)
            let document = new PersonCouchDocument("123456", "John Doe", "123 Main")
            x.couchServer.Repository.Save(document)
            x.bus.Send("SymbioteDemo", document)
            let documentRetrieved = 
                x.couchServer.Repository.Get<PersonCouchDocument>(document.DocumentId);
            do Console.WriteLine(
                "The document with name {0} and address {1} was retrieved successfully", 
                documentRetrieved.Name, documentRetrieved.Address)
            do x.couchServer.DeleteDatabase<PersonCouchDocument>()
        member x.Stop () =
            do Console.WriteLine("The service has stopped")

do Assimilate
    .Core()
    .Daemon(fun x -> (x.Name("FSharpDemoService")
                                    .DisplayName("An FSharp Demo Service")
                                    .Description("An FSharp Demo Service")
                                    .Arguments([||]) |> ignore))
    .Relax(fun x -> x.Server("localhost") |> ignore) 
    .Jackalope(fun x -> x.AddServer(fun s -> s.Address("localhost").AMQP08() |> ignore) |> ignore)
    .RunDaemon() 


Conclusion:

As mentioned previously, with the help of Symbiote it only takes a dozen or so additional lines of code to add support for RabbitMQ to our previous example.  The complete source for this solution can be found at http://github.com/dmohl/Symbiote-Jackalope-Example.