Creating a VSPackage with F#

Ever since Mattox Beckman introduced the OCaml language to those of us lucky enough to be in his "Languages and Compilers" course back at UIUC, I've had an interest in functional languages.

A few months ago, Soma announced that Microsoft will be turning F# (a variant of OCaml that runs on .NET) into a fully supported product.

Since then, I've been meaning to try and see if I could create a simple VSPackage using F# and get it loaded and working in the IDE. I'm pleased to report that this is indeed possible, although it requires a few manual steps (due to F# not having support for MSBuild at the present time). Besides the VSCT file used to statically define the menu command, here is the entirety of the code for the package. All this package does is add a menu command to the Tools menu (via VSCT) and add a handler for it at runtime here:

#light
namespace FSharpPackage
open System
open System.ComponentModel.Design
open System.Runtime.InteropServices
open Microsoft.VisualStudio.Shell
open Microsoft.VisualStudio.Shell.Interop

[<GuidAttribute("5b1edd5f-eda1-40b5-9fe3-e8f3af42297f")>]
[<DefaultRegistryRoot("Software\Microsoft\VisualStudio\9.0Exp")>]
[<ProvideMenuResource(1000s, 1)>]
[<PackageRegistration(UseManagedResourcesOnly=true)>]
type MyPackage() =
class
inherit Package() as base

        let commandSetGuid = "fa6884a3-2efb-43c6-81e5-2a03fb39a7d8"
let menuExecuteHandler = new EventHandler(fun _ _ -> ignore(System.Windows.Forms.MessageBox.Show("Inside F# function!")))
let commandId = 0x100

        override x.Initialize() =
base.Initialize()
let menuService = base.GetService(type(IMenuCommandService)) :?> OleMenuCommandService
menuService.AddCommand(new OleMenuCommand(menuExecuteHandler, new CommandID(new Guid(commandSetGuid), commandId)))
end

To try this out on your own machine (with VS 2008 + VS 2008 SDK + F#), do the following:

  1. Download the sources from the MSDN Code Gallery & unzip to a folder on your machine
  2. Open a command prompt
  3. Ensure that the F# tools (fsc.exe, resxc.exe) are on the PATH
  4. Navigate to the folder from Step 1, and run build.bat
  5. Launch the VS Experimental hive (devenv /ranu /rootsuffix Exp)

You should then see a command called "My Command FSharp" in the Tools menu.

This package doesn't really do anything fancy that leverages F#, and certainly, you could approach this another way (e.g. create your library in F# and call into it with a typical VSPackage coded in C#, etc...). Nevertheless, it's still neat to see that it's possible. :-)