Category Archives: F#

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!

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

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.

F#– WPF Component Development

This post will only deal about using F# for WPF custom component development; it is considered that the user has already knowledge about WPF custom control development.

The current F# support for VS2010 is lagging in some ways,

· Can’t create a folder, this directly affects the way we can define the generic.xaml file.

· XAML -> BAML conversion with MSBuild task

We can do workarounds in both the cases and make component development using F# language and that is what we are going to discuss here. If there is any other better way to go for it, do let me know in your comments.

Creating Folders in an F# project

Till the F# team include this support in VS2010 we need to do the below workaround,

· Edit the .fsproj in Notepad.

· Add the below line in <ItemGroup>

.fsproj code

<Resource Include="Themes\generic.xaml" />

<Compile Include=”NewFolder\somefile.fs” />

XAML to BAML conversion through code

WPF has an API Application.LoadComponent(Uri) which loads a resource, although it is a bit slow. For a WPF component to load its inner template, it requires the generic.xaml file to be loaded when the control is initialized. In WPF C# custom control library, the below code does that automatically,

C# Code

public class CustomControl1 : Control

{

static CustomControl1()

{

DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new FrameworkPropertyMetadata(typeof(CustomControl1)));

}

}

Or we can just have the DefaultStyleKey overridden in the constructor,

C# Code

public class CustomControl1 : Control

{

public CustomControl1()

{

this.DefaultStyleKey = typeof(CustomControl1);

}

}

F# Solution

BAML conversion doesn’t work in F# because the MSBuild targets project for F# has issues when building the generic.xaml as a “Page” element.

On further investigation, I found that we can manually do the steps through code and make the control apply the template defined in XAML. Below are the steps that needs to be done,

1. Override the “DefaultStyleKey” property,

do this.DefaultStyleKey <- typeof<WatermarkTextBox>

2. Load the resource file and merge it to the control’s resources collection,

let resourceDict = Application.LoadComponent(new Uri("/FSharp.SampleControls.Wpf;component/Themes/generic.xaml", System.UriKind.Relative)) :?> ResourceDictionary

do this.Resources.MergedDictionaries.Add(resourceDict)

This will ensure that the control template is implicitly set to the control, you also have the OnApplyTemplate() getting called when you override that method. That’s it; we have loaded the control template and enabled the custom control to load like a normal WPF component. I also tested by editing the control’s Style using Blend and that also worked,

clip_image002

The full test sample is available in this link. The project contains a simple implementation of a WatermarkTextBox as a WPF custom control; it also has a C# WPF application that uses it.

I have also prepared a simple F# WPF custom control library project, You can download that from this link. You have to place this in the “Project Templates” location,

Windows 7

C:\Users\{UserName}\Documents\Visual Studio 2010\Templates\ProjectTemplates

This should enable VS2010 to load the template.

F# “fun” with Windows Phone 7

 

Don syme announced the availability of F# for Windows Phone 7 (link). Daniel Mohl has a project template for F# apps that Don showed in the F# community demo (link).

Note: Anyone wanting to start off a project from scratch can download the project template that I created from here. This is a simple F# WP7 app template without the extra demo files.

As with my previous posts (long back, can’t find enough time these days), I ported the Stock ticker code base to WP7. The UI is pretty simple, It only has a ListBox to show the stock data. The ListBox has a custom ItemTemplate that defines the layout for the input data pulled over the web (Yahoo finance). The application also checks for network connectivity. Below is a snapshot,

image

This sample only pulls the stocks when you click the button, Since it is used in a phone, actual CEP kind of scenario would not be suitable, so keeping the updates in deferred mode. UI polishing + added features would make this a good app for the market store, what do you think? 😉

Sample with source code link.

-Fahad

CEP Client – Remix (WPF & SL)

My previous post had implementation of Rx + F# + Syncfusion WPF GridDataControl. This post is a continuation with a cleaner sample + a Silverlight 4 client using the same abstractions. The technologies used are,

· Rx (http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx), Download the latest version for Silverlight.

· F# – (http://www.silverlight.net/getstarted/silverlight-4/) Get the latest SL4 tools for VS2010, it includes a copy of Fsharp.Core.dll built for the SL 4 Framework.

The sample code is much the same; it uses code sharing between the WPF / SL source projects with some conditional compilation constants to make it build properly. One more caveat is that, since we doing a Webrequest call over the network, we need elevated permissions to do in a Silverlight application, without this we would have to host a client access policy file in the server. Only way is to run the SL application in an elevated trust.

Silverlight 4 – Out Of Browser application,

image

You would have to send me an email again to get the sample code. May be if I get more time, I can work on this and make it colorful to host it in our site itself :).

-Fahad