Archive for March, 2009

F# Seq.fold

A lot of the business code we tend to write deals with taking some collection and producing some fact about that collection. Examples include:

• Taking all the line items in a sales order and producing a total value of the order.
• Concatenating a set of order lines to create an order.

In F#, one can take a sequence of items and fold it to return another item representing some truth about that collection. This is done via the Seq.fold function. Typical invocation involves taking some collection, passing that collection via the pipeline operator, |>, to Seq.fold. Seq.fold then takes a function that has two values passed to it: an accumulator and the next value in the collection. Each value is folded into the accumulator in some fashion– if summing up numbers or concatenating strings, the accumulator is just another number or string. On each successive iteration, the return value appears as the accumulator to do more work. The accumulator can also be a different type from the list. Below, we have two examples:

• sum x calculates the sum of a sequence of numbers.
• concantenate x takes a sequence of objects and returns the result of concatenating all the string representations together. The example uses the characters ‘a’ to ‘z’.

1 #light

2

3 open System

4 let numbers =[1..100]

5 let letters=[‘a’..‘z’]

6

7 let sum x = x |> Seq.fold(fun acc a -> acc + a) 0

8 let concatenate x =

9     x |> Seq.fold(fun acc a -> String.Format("{0}{1}", acc, a)) ""

10

11 let doWork=

12     printfn("%d") (sum numbers)

13     printfn("%s") (concatenate letters)

This writes:

5050
abcdefghijklmnopqrstuvwxyz

Yet another nifty technique to add to your toolbox.

Method Overloading in F#

In my goal to learn F# better, I’m doing all of my recreational development in the language. This gives me lots of learning opportunities (better known as WTF moments). I was implementing a MembershipProvider for an ASP.NET web site where the datastore is not SQL. By and large, MembershipProvider requires that you implement uniquely named methods. It does exposes a pair of abstract methods that one must implement. In C#, they look like this:

public abstract MembershipUser GetUser(

string username,

bool userIsOnline);

public abstract MembershipUser GetUser(

Object providerUserKey,

bool userIsOnline);

These two methods seemed pretty natural to overload in F#. I just wrote these stubs:

override this.GetUser(providerUserKey: obj, userIsOnline: bool) : MembershipUser =

null

override this.GetUser(userName: string, userIsOnline: bool) : MembershipUser =

null

The compiler didn’t like this, telling me

`Duplicate definition of value 'AwsMembershipProvider.GetUser.3.override'`

No amount of fiddling with the signature produced results. I was at a loss, so I pulled out the Object Browser in VisualStudio and focused on the FSharp.Core assembly. This looked like a job for a special attribute– F# seems to handle interop with the object oriented world via attributes and a few keywords. None of the keywords looked right. That’s when I found Microsoft.FSharp.Core.OverloadIDAttribute. Clicking on the class in the object browser, I learned this:

Adding the OverloadID attribute to a member permits it to be part of a group overloaded by the same name and arity. The string must be a unique name amongst those in the overload set. Overrides of this method, if permitted, must be given the same OverloadID, and the OverloadID must be specified in both signature and implementation files if signature files are used.

Now I got it– the overload didn’t work because both methods had the same arity (number of arguments). I needed to tell the compiler that these two methods looked the same, but have different IDs for the overload set. This is what got me to compile:

[<OverloadID("GetUser.obj.bool")>]

override this.GetUser(providerUserKey: obj, userIsOnline: bool) : MembershipUser =

null

[<OverloadID("GetUser.string.bool")>]

override this.GetUser(userName: string, userIsOnline: bool) : MembershipUser =

null

Crossdomain Silverlight Hosting

At work, I had a need for a line of business monitoring application to figure out server health. Due to the nature of the monitoring, it made sense to write this as a MySpace Developer Platform application, hosted in the browser. The display needs required a Rich Internet Application interface, meaning Flash, Silverlight, or heavy AJAX. I chose Silverlight, just because. Now, MySpace doesn’t allow one to publish a Silverlight application, but that didn’t stop me from writing an app for my own personal consumption. Given the nature of the application, I needed to host the Silverlight XAP file on a server separated from the JavaScript and web page that displayed the application. Silverlight doesn’t like having JavaScript call into it unless the application manifest says that it is OK. It took me several hours to figure out the nature of why my scriptable objects, which worked fine in my test environment, failed in production. Living on two servers busted things. If you host the Silverlight XAP file on a domain that is separate from your web page, you need to declare the following in the Silverlight application’s manifest:

<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment"

ExternalCallersFromCrossDomain="ScriptableOnly">

<Deployment.Parts>

</Deployment.Parts>

</Deployment>

ExternalCallersFromCrossDomain supports two values: NoAccess and ScriptableOnly. It is secure by default, setting NoAccess. Since I needed JavaScript from a different domain (a different web site) to access the scriptable members of the, I had to set this to ScriptableOnly.

FWIW, this bug followed the Seely Bug Fix Complexity Rule: the longer you spend troubleshooting a bug, the smaller the fix will be. Time spent troubleshooting: 4 hours. The bolded item above shows the fix.

Dollhouse Blows

I just got done reading Penny-Arcade’s 2009-2-27 post on Joss Whedon’s Dollhouse. I had high expectations for this show. I waited for the show to be ready for my Media Center to record on a regular basis. The promos looked interesting and he did have a reputation. A few weeks ago, that first show appeared in Recorded Shows on my computer. My wife and I fired it up. 20 minutes into the show, we looked at each other, said "This is crap. Let’s delete this thing from our regular recordings and go wash the dishes." Yes, dishwashing was more appealing than watching the remainder of the show. Furthermore, we had no desire to assault our senses with the show EVER AGAIN!!! The acting was horrible, the premise sucked (reminded by of My Own Worst Enemy without the decent actors). Maybe Whedon should listen to his comedy muse instead of the other ones. He wrote Buffy The Vampire Slayer. The translation to a TV show sucked. His recent work in 2008 on Dr. Horrible’s Sing Along Blog was a riot! The guy knows funny! But, his serious stuff makes me shudder.

Hosting Silverlight on Google App Engine

Recently, I needed a place to store a compiled Silverlight assembly in a highly available environment. Ideally, the location needed to be free or on some web site that I owned. Since I’ve been getting comfortable with App Engine lately, I figured I would try setting up app-engine to host my file. The one thing that you need to do when return a Silverlight XAP file is make sure that it comes back with the MIME type set to application/x-silverlight-app. It turns out that this is pretty simple. I just added this to my app.yaml file:

`handlers:`

`- url: /SilverlightApp.xap`

`  static_files: SilverlightApp.xap`

`  upload: SilverlightApp.xap`

`  mime_type: application/x-silverlight-app`

` `

With this, I have App Engine reliably serving up my page with Silverlight embedded.