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.