Creating F# TypeProviders with VS Experimental Instance

Blogging after a long time now! So after a big break I started to look at F# TypeProviders for the first time, the samples from fsharp3sample.codeplex.com were good enough to get me started. So as soon as I wrote the Hello world kind of code and executed thru the interactive window I wanted to try out some changes and see the updated types. Now I was trying to compile the source and it wasn’t allowing me to do it, the dll was getting referenced by Visual Studio. I had to close the VS instance and then open again to re-work with it, this is quite annoying as I’m a newbie and I would like to explore the TypeProviders slowly to understand how it works. I asked around in Twitter to see if someone had a better solution to this, and I got a reply from @sforkmann

@sforkmann: @fahadsuhaib I’m always using two VS instances. Having a fast SSD helps a lot.

Now opening up 2 VS instances rang some bells, I thought to use the VS experimental instance to fire up when I need to check the TypeProvider and then close it to ensure that I don’t need to close all the VS instances. It just gives a simpler way to do “debug” like execution and then go back to make some changes in my TypeProvider. Below are the steps to enable VS Experimental Instance,

  • Right-Click the TypeProvider project and goto its properties window
  • Navigate to the “Debug” tab and set the following,
    • Start external program: c:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe
    • Command line arguments: /RootSuffix Exp

sshot-3

Note: I haven’t upgraded to VS2012 yet (on vacation still Smile) but it should work the same way.

Now that we have the VS setup to use Experimental instance, we hit the “Play” button to start the instance (this will fire off another VS instance one that is used for testing with VS addins). We need to create another test F# project that will use the TypeProvider library. Below are the steps,

  1. Run the TypeProvider library project
  2. Create a new F# console app to test the TP
  3. Add reference to the TP library in the F# application project, this will ensure that the dll is copied to the bin\debug location. It helps a bit in copying the dll out of the original location and not locking the original dll to VS instance
  4. Build the project
  5. Add a new F# script file for testing in interactive mode
  6. Add references to the TP library in the F# script file
  7. This will popup a dialog asking you to enable/disable the plugin to load. Click “disable” for now as we will enable it in the next step
  8. Once everything is setup, you can navigate to Tools –> Options –> F# Tools –> Type Providers and select the checkbox to enable it
  9. Check out your TP in this step
  10. When you are done, close the Experimental VS and navigate to Tools –> Options –> F# Tools –> Type Providers in the TP library project. Uncheck the TP that you had used before, this will ensure that VS is no longer holding on to that instance.
  11. Make changes to your TP library and repeat the steps if you want to test again.

There are couple of manual steps which are really painful to repeat, but it is far better than having 2 VS instances side-by-side and closing/opening them often! So a final treat, as there are lots of steps above, I recorded a simple video,

Note: Don’t ask me what I was working on, it was just a simple experiment with Zackbray’s GUI framework. It dint work because generic types are not supported in TP’s yet. Hopefully once it gets added, I’ll work on it again!

F# for Beginners – II

I was a bit busy over the last month working for a client in F#, and so couldn’t find good time to prepare for the second part. I also thought to keep the videos smaller so I can have time to prepare more content in short periods.

In this part you will be learning about the following,

  • Data Types
  • let keyword
  • Recursion
  • Pipelining

We have some enhancements in this tutorial, You get to view the video with proper sound efffects. And you also get to read the PDF document with more clear type font Smile.

Part 2

Download the content and slides from this link. Let me know what do you think about this!

- Fahad

Silverlight Navigation Frame in F#

This is again a quick post based on my daily findings as I work more into Silverlight and other frameworks with F#. The Silverlight Navigation Frame allows us to provide deep linking within Silverlight applications. It uses a NavigationFrame control and hosts a “Page” instead of UserControl. This is very useful when developing large enterprise apps and also provides SEO friendly URIs (if you are building something online).

I faced a couple of problems when using F#, because the Navigation frames were based purely on XAML code and it interacted with the C# code using partial classes. As you all know F# doesn’t provide “partial” classes, I was looking to find an alternative to customize this design. Luckily with Silverlight 4, the navigation frame includes a “ContentLoader” property which is of type INavigationContentLoader. It has some extensible methods that allows customization to define the mapping, that was it and I implemented the below code to wrap it around Types instead of plain URIs. This would allow the navigation frame to invoke an object of the type and then we load the Page in the implementation of the type. This lets us use F# code purely with XAML to be used for UI declaration.

type TypeContentLoader() =
    
    let getTypeNameFromUri(uri : Uri) =
        let mutable contentUri = uri
        if not(uri.IsAbsoluteUri) then
            contentUri <- new Uri(new Uri("dummy:///", UriKind.Absolute), uri.OriginalString)
        Uri.UnescapeDataString(contentUri.AbsolutePath.Substring(1))

    interface INavigationContentLoader with
    
        member x.CanLoad(targetUri : Uri, currentUri : Uri) =
            let typeName = getTypeNameFromUri(targetUri)
            let t = Type.GetType(typeName, false, true)
            let mutable result = true
            if t = null then
                result <- false
            let defaultConstructor = t.GetConstructor(Array.empty<Type>)
            if defaultConstructor = null then
                result <- false
            result

        member x.CancelLoad(asyncResult : IAsyncResult) =
            ()

        member x.BeginLoad(targetUri : Uri, currentUri : Uri, userCallback : AsyncCallback, asyncState : obj) =
            let t = Type.GetType(getTypeNameFromUri(targetUri), false, true)
            let instance = Activator.CreateInstance(t)         
            let asyncResult = new AsyncResultNoResult(userCallback, asyncState)   
            asyncResult.Result <- instance
            asyncResult.SetAsCompleted(null, true)
            upcast asyncResult            
            
        member x.EndLoad(asyncResult : IAsyncResult) =
            let container = asyncResult : ?> AsyncResultNoResult            
            new LoadResult(container.Result)

 

We simply set the navigation frame’s ContentLoader property with the above instance,

        <sdk:Frame x:Name="ContentFrame"
                   Grid.Row="1">
            <sdk:Frame.ContentLoader>
                <common:TypeContentLoader />
            </sdk:Frame.ContentLoader>
        </sdk:Frame>

 

Then declare a HyperlinkButton to navigate to the particular type,

            <HyperlinkButton Content="Home"
                             NavigateUri="FSharpSilverlightApp1.Home"
                             TargetName="ContentFrame"
                             Margin="4" />

That’s it, It is now easy to separate your view concerns based on namespaces. Hope this helps in using F# more easily!

Download the sample from here.

-Fahad

Bing RESX .NET Helper

I’m working on one consulting project in Silverlight and it had lots of localization features to be done, I had to construct the English language so that was easy. After that it was the turn for converting this RESX to 4 other languages, By the thought of doing it line-by-line I was more sleepy and lazy!

I did remember that once Dr. Don Syme had shown some samples of using Bing translator in JAOO tutorials. Quickly took that sample source and looked over it for 5 mins to get this working in this use case. Then it hardly took 20 mins to put up a script file and get my work done, that was the sweet spot, I did the below things,

  • Connected to BING API service “async”hronously
  • Read from the resources txt file
  • Passed each line to BING for translating
    • Each request is a parallel execution
    • Used async continuations to process out the results

That’s it, so it just took 20 mins and saved me the whole day’s work! I’m pretty sure most .NET apps have requirement of having it localized in various languages, this is one way to get your work done. You can take a look at the source code in github, https://github.com/fahadsuhaib/FSharpTools. Check out the readme to know how to use it.

-Fahad

You can follow me on Twitter – @fahadsuhaib

F# for Beginners–I

I’m starting off a series of video tutorials for F# language. This would be for beginner’s initially, looking at different aspects of the F# language and its integration with Visual Studio 2010. The tutorial would contain a video post along with a study material in PDF. The first tutorial contains the below content,

  • Using Visual Studio 2010
  • F# Program Structure
  • F# file organization
  • F# Scripts

Download the PDF document from here.

F# Quotations for INotifyPropertyChanged

I was wanting to use F# quotations with INotifyPropertyChanged for quite sometime now, Since I’m working on pure usage of F# in WPF and Silverlight this is one part that would help using F# with Visual Studio. There are lots of ViewModelBase implementation in C# that utilizes the LINQ expressions when you want to declare CLR properties. The LINQ Expression<Func> allows you to write strongly typed code in C# for defining the property,

private object selectedItem = null
public object SelectedItem
{
	get{ return this.selectedItem; }
	set
	{
		if(this.selectedItem != value)
		{
			this.selectedItem = value;
			this.OnPropertyChanged(() => this.SelectedItem)
		}
	}
}

The above code uses a strongly-typed OnPropertyChanged method that in-turn parses out the property name and passes that to the INotifyPropertyChanged interface.

Now that I’m officially working on full-time F# work, I was happy to get this done. Below code shows the ViewModelBase implementation utilizing the F# quotations,

open System
open System.Collections.ObjectModel
open System.ComponentModel
open Microsoft.FSharp.Quotations
open Microsoft.FSharp.Quotations.Patterns

type ViewModelBase() =
    let propertyChanged = new Event<_, _>()
    let toPropName(query : Expr) = 
        match query with
        | PropertyGet(a, b, list) ->
            b.Name
        | _ -> ""

    interface INotifyPropertyChanged with
        [<CLIEvent>]
        member x.PropertyChanged = propertyChanged.Publish

    abstract member OnPropertyChanged: string -> unit
    default x.OnPropertyChanged(propertyName : string) =
        propertyChanged.Trigger(x, new PropertyChangedEventArgs(propertyName))

    member x.OnPropertyChanged(expr : Expr) =
        let propName = toPropName(expr)
        x.OnPropertyChanged(propName)

To use the above, You need to inherit the ViewModelBase to your custom type and then call the OnPropertyChanged method with the F# quotations. Below is an example showing how to declare the same “SelectedItem” property in F#,

    let mutable selectedItem : obj = null

    member x.SelectedItem
        with get() = selectedItem
        and set(v : obj) = 
            selectedItem <- v
            x.OnPropertyChanged(<@ x.SelectedItem @>)

The F# quotations are wrapped around <@@> block, this is the syntax in F#. Now you get full intelli-sense with Visual Studio too,

image

Also, added this in the F# snippets site here.

Hope this helps.

-Fahad

WPF / Silverlight DependencyProperty in F#

This is a quick post to share on how-to declare WPF / Silverlight DependencyProperty in F#. The reason, In F# there are no public static fields to declare. Read all about DPs (DependencyProperty in short) here. If you are developing a WPF / Silverlight solution libraries completely in F#, then you would have to declare DPs so you can expose the functionality to be used in any .NET language.

Let’s say we have an ItemsSource property to declare, below is the way it has to be declared,

    [<DefaultValue>]
    static val mutable private ItemsSourcePropertyInternal : DependencyProperty

    static member ItemsSourceProperty
        with get() =
            if CustomControl.ItemsSourcePropertyInternal = null then
                CustomControl.ItemsSourcePropertyInternal <- DependencyProperty.Register("ItemsSource", typeof<IEnumerable>, typeof<CustomControl>, new PropertyMetadata(null))
            CustomControl.ItemsSourcePropertyInternal

    member x.ItemsSource
        with get() = x.GetValue(CustomControl.ItemsSourceProperty) : ? > IEnumerable
        and set(v : IEnumerable) = x.SetValue(CustomControl.ItemsSourceProperty, v)

 

  1. Declare a private mutable variable that registers the DependencyProperty
  2. Write a static member variable with a getter that initializes the DP
  3. Declare the member property with a getter and setter.
    1. Important thing to note in the setter is to decorate the value “v” with the type. This is because of the fact that when this property gets exposed to other .NET languages like C# or VB, it causes errors assigning un-typed values to the property.

In WPF, there is a caveat. WPF can invoke private / internal field variables too from XAML, rather Silverlight can only invoke public variables from XAML. So we don’t require the notion of creating a private mutable static field (If we don’t wish to expose it). The same ItemsSource property can be declared as below In WPF,

    static let ItemsSourceProperty = DependencyProperty.Register("ItemsSource", typeof<IEnumerable>, typeof<SearchTwitterBox>, new PropertyMetadata(null))
    member x.ItemsSource 
        with get() = x.GetValue(ItemsSourceProperty) : ? > IEnumerable
        and set(v : IEnumerable) = x.SetValue(ItemsSourceProperty, v)

We won’t be able to expose the DP here, but it does work if you don’t want to expose the DP.

That’s it!

-Fahad

F#–In the Enterprise III

In our previous posts here and here, we looked at why and how F# can be used with WPF. Today we will check out how to create a real-world application using F# and WPF (with MVVM pattern). We would check this out using a video tutorial, (which is more intuitive and less time consuming to read a big post). Below is the app architecture,

App architecture Note: To start developing twitter apps, You should first get registered in dev.twitter.com and get the access token and secret.

There are three main areas that defines the application,

  1. oAuth – To get authorization with Twitter
  2. Download Agent – F# Agent worker that connects to Twitter with oAuth and parses the tweets from XML response stream.
  3. MVVM – The whole app is built around MVVM

OAuth in Twitter

OAuth requires a series of steps to execute and get the authorization key and secret. You can find more details here. In our sample we have a script file(twitter_oauth.fsx) that shows how to get the token and the secret, Execute the below code,

// Execute the below three lines first and then copy-paste the verifier code that Twitter gives you
let oauth_token'', oauth_token_secret'', oauth_callback_confirmed = OAuth.requestToken()
let url = OAuth.authorizeURI + "?oauth_token=" + oauth_token''
System.Diagnostics.Process.Start(url) |> ignore

This will start off the your browser to allow access to this app,

twitter_oauth

This will give you a “verifier” code which you need to use to get your private access token and secret.

let mutable verifier = ""
let oauth_token, oauth_token_secret = OAuth.accessToken(oauth_token'', oauth_token_secret'', verifier)
printfn "%s" oauth_token
printfn "%s" oauth_token_secret

 

Now  you are good to go ahead and start writing the Twitter app. The Twitter app contains an agent worker to pull the data from twitter and a simple observable collection to push the data into the UI.

We also use some async helpers that lets us marshal from background thread to the UI thread using SynchronizationContext. Check the “AsyncHelpers.fs” for more details.

Video

F#–In the Enterprise

Download the source from here. The sample project doesn’t contain the consumer key / secret as well as the oauth key and secret, you need to manually replace them to run the application.

F#–In the Enterprise – II

In the previous post we only looked into the problems we face in adopting F# as a language in our daily development work. The idea in this post is to show how adoption of F# is easy. We will look into creating complete WPF apps using F# without any UI separation code with C# or any other .NET language. There is no reason behind following this model, but it shows how to adopt F# with WPF / Silverlight UI platforms. We do use some workarounds in the way to achieve our goal, but then if you want to fully adopt then this certainly is one way to do it.

As we already had looked into the MVVM pattern, it gives a nice separation of code from the UI with the Model that drives the UI.

image

We will only check out the how-tos to create a WPF application and get it up and running with pure F# code.

Creating a WPF Application with F#

1. File –> New Project –> Visual F# –> F# Application

image

2. Add references to WPF related assemblies,

  • PresentationCore.dll
  • PresentationFramework.dll
  • WindowsBase.dll
  • System.Xaml.dll (.NET 4.0 FW)
  • UIAutomationTypes.dll

3. Open Program.fs and add the below code,

open System
open System.Windows

[<STAThread>]
[<EntryPoint>]
let main(_) =
    0

4. Next, we add an XML file with .xaml as the extension. This is a workaround may be in future version of F# we may have a XAML template to directly add it. Just name it “Window1.xaml” and add the below code,

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
                  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    
                  Width="640" Height="480">    
</Window>

Note: Make sure that Window1.xaml is set to "Resource”. Click on the Window1.xaml file and view its properties to change the build action to “Resource”.

image

5. Lets design some markup just for the demo. It has a simple Grid panel with TextBox, Button and a TextBlock data-binded to the TextBox. We also listen to the click event and show a Message window with the TextBox.Text value. One more important thing is that we use Visual Studio to do the designing.

6. We now need to connect this code with the application and run it. We will also add up some utility functions that would help load this XAML file. Please check the full WpfUtils.fs in the sample attached in the end of this post.

7. Add a new F# file named “Window1.xaml.fs” and add the below code,

namespace iBlue.Demos

open System
open System.Windows
open System.Windows.Controls
open WpfUtils

type Window1() =
    
    let window = WpfUtils.LoadXAML<Window>(new Uri("/MyFirstFApp;component/Window1.xaml", UriKind.Relative))
    let btnClick : Button = window?btnClick
    do btnClick.Click.Add(fun _ -> MessageBox.Show("Clicked") |> ignore)

    member x.Instance with get() = window

Note: F# doesn’t have the notion of partial classes. We simply define the name as “Window1.xaml.fs” without any implementation of the actual window.

Some important points to note in the above code snippet,

LoadXAML<T>

This method uses Application.LoadComponent based on the Uri specified. Remember we already defined the Window1.xaml as an “Embedded Resource”, the Uri takes the parameters based on this convention and passes on to the Application.LoadComponent method.

source?name

This is a convention to find the element in the visual tree of the application. If we declare a UIElement with x:Name attribute, we can then use this notation to identify the element and use it to do some code-behind operations. In the above code it simply shows a message “Clicked”.

Note: Ideal way to deal with maintaining a Window instance is to do all XAML code in UserControl, and then use them to set the content of the Window through F# code.

8. The final step is to load up the window from the entry point (“Program.fs”) code.

open System
open System.Windows
open iBlue.Demos

[<STAThread>]
[<EntryPoint>]
let main(_) =
    
    let window = new Window1()
    let app = new Application()
    app.Run(window.Instance)    

9. Hit F5 to run the application.

image

That’s it, We now have a full fledged WPF application that completely runs on F# code. Although it required a bit of learning curve, it is still relatively easy to understand WPF and make it easily usable with F# code. Download the sample from here.

In the next post we will do a video tutorial on creating a small time Twitter application and walkthrough the details of the Application using MVVM pattern.

F# – In the Enterprise – I

This will be a series of posts on how-to use F# in the enterprise. I will strictly reduce this post to Windows based enterprise apps and it is not a debate about using F# over C#, it is more using Functional programming over pure OOP, And the ways in which we can use F# in different domains. Below are some common questions that you would see people asking around,

  • Who and how is F# being used in Enterprise
  • The tooling is not that good for Windows Forms / WPF platforms
  • What impact does this make in developing apps, Does FP reduces the time and effort that you put in?

We will also take a look at how F# can be used in all these different thick client application platforms that we normally use. And also, how and when F# can be used in these application platforms.

Windows Forms Client Apps

Most day-to-day work by WF programmers can be categorized as below,

image

Work is mostly with UI design using Visual Studio designer and develop apps real quick with minimal code behind. The DB layer also involves minimal code as the apps would normally use LINQ / DataSet designer to generate the middle layer.

Using F# right now with minimal designer support would be a heck lot of problems. There would be too much of code to write the connection between the UI and designer. This may be lot of work to get all the tooling support up and running in Visual Studio. May be we can expect this in VS2012 or future.

There are other kinds of apps in which it requires more technical analysis based on the problem domain. Consider writing apps for 3D, high-frequency stock trading, complex measurement units, high-level data-structures for charting etc., For these domains where you find the complexity needs to be addressed in a more concrete manner, F# is the right tool to use. As F# brings in more functional way of writing code, and easy abstraction over OOP to use with other languages.

Points to take from this,

  • Don’t use direct F# code if it is heavily relying on UI + DataBase. Unless you really want to take the pain of using it.
  • If you find a complex problem domain, then try identifying the complexity in it and see if F# can really help. To make this decision, You need to know how F# can be used, It is not a decision to be made by someone who is learning F# or not knowing the language.
  • Always build an OOP abstraction over F# code so it can be easily used with other languages (C# or VB.NET).

WPF Client Apps

WPF provides a new UX platform running on latest Windows OS. It’s core fundamental UX works with separation of UI code in XAML (a derivation of XML) and the Model provided to the UI. In 2005, John Gossman, currently one of the WPF and Silverlight Architects at Microsoft, unveiled the Model-View-ViewModel (MVVM) pattern on his blog. MVVM is identical to Fowler’s Presentation Model, in that both patterns feature an abstraction of a View, which contains a View’s state and behavior. Fowler introduced Presentation Model as a means of creating a UI platform-independent abstraction of a View, whereas Gossman introduced MVVM as a standardized way to leverage core features of WPF to simplify the creation of user interfaces. In that sense, I consider MVVM to be a specialization of the more general PM pattern, tailor-made for the WPF and Silverlight platforms.

image

F# fits very nicely when using MVVM pattern of development in WPF applications. Since most WPF developers prefer using MVVM as a pattern when developing WPF apps, it is really easy to use F# as the first-level language to build a full-fledged WPF app.

Of course, some developers may use heavy designer generated WPF app, but there is a difference in the way WPF designer works compared to Windows Forms. So once the WPF form gets designed, we can use pluggable F# code that can simply work out easily.

We will look into creating F# based WPF apps in the next post, and understand the small steps that we need to change to make it work.

Follow

Get every new post delivered to your Inbox.