Creating Web Parts with F#
F# is an interesting language, especially for creating Embedded Domain Specific Languages (EDSLs). This article by Brian McNamara on a little “Turtle Graphics” implementation with Silverlight got me thinking about how F# could be used in web parts. Anyway, the starting point is creating a web part using F#, so that’s what this blog entry is about. First, here’s the code for a “Hello World” web part:
#light namespace FSWebPart open System.Web open System.Web.UI open System.Web.UI.WebControls open System.Web.UI.WebControls.WebParts type public HelloWorldWP() = inherit WebPart() override x.Render (writer:HtmlTextWriter) = writer.Write("Hello World")
The code is completely equivalent to C# web part code: define a namespace, import namespaces, define a type (class) that inherits from “Web Part” and provide an overload for the “Render” method.
Here’s how to build and test the web part using Visual Studio 2008. It’s not quite as straightforward as with C# as the web part is not available in the toolbox. Also, this example does not sign the assembly so it’s not ready for SharePoint.
In Visual Studio 2008:
Create a new project using the F# Library project template. Call this project FSWebPart.
Add an F# Source File into which the above code should be placed. Name this file HelloWorldWP.fs. You can delete the fs file created with the project.
Build the project.
You can now add a web project to the solution which will be used to test the web part.
Add a “New Web Site” project to your solution. Call this web site WebSite.
A reference to the F# project will need to be created in this new web project. You must create a reference using the “Browse” facility to locate the assembly – do not use a project reference.
Right click the WebSite project and select Add Reference.
Click the Browse tab and select t the assembly FSWebPart.dll.
The Default.aspx page will now be modified to include a web part manager, a web part zone and to add an instance of the “HelloWorldWP” web part to the web part zone:
Open default.aspx in “source” view.
Drag and drop a WebPartManager control from the Toolbox, WebParts section, under the <body> tag in default.aspx.
Drag a WebPartZone control and drop under the </div> tag.
Add the following Register directive under the “Page” directive:
<%@ Register assembly=”FSWebPart” namespace=”FSWebPart” tagprefix=”cc2″ %>
Now add a tag in the <ZoneTemplate> tag to create an instance of our web part:
<asp:WebPartZone ID=”WebPartZone1″ runat=”server”>
<cc2:HelloWorldWP ID=”One” runat=”server” />
Compile and test the web part. It should be displayed in the ASPX page.
If you’re interested in finding out more about the F# language try these two sources:
Update: 12-May-2010: See this next post to find out how to write an EDSL for outputing Table Tags!