In Part 4 we did Exercise 1 of WATK’s Introduction to Cloud Services lab, putting most of the code in F# libraries. In this part we’ll finish the lab.
In Exercise 2 we create the worker role. This is the only kind of F# project that the Azure SDK provides out of the box. We follow Task 1 Step 4 in the manual and choose F# worker role instead of C#.
As usual, we can delete the reference to System.Numerics, and we add references to System.Drawing, System.Data.Services.Client, Microsoft.WindowsAzure.StorageClient, Guestbook_Data and GuestBook_Storage.
The code for converting images to thumbnails doesn’t depend on Azure, so it makes sense to put it in a separate source file named ImageProcessing.fs. In a real solution we’d probably use a separate graphics library.
We now replace the entire contents of WorkerRole.fs. The code is a bit shorter than the C# original because we can re-use the storage initialization we wrote in Part 4.
Notice in On_Start() the call to CloudStorageAccount.SetConfigurationSettingPublisher(). It looks quite different from its C# equivalent because F# doesn’t sugar Action and Func delegates to make them look like F# functions. The argument we pass to CloudStorageAccount.SetConfigurationSettingPublisher() must be an Action<string, Func<string, bool>>. When we modified Global.asax.cs in Part 4 we were able to write this in C# as a simple lambda expression.
But in F# we have to explicitly declare that the Action and its Func argument are delegates, and we must call the Func using its Invoke() method. Furthermore, F# won’t let us avoid dealing with the value returned by a Func, as C# casually does. On the other hand, F# offers the pipe-forward operator, which makes the code easier to follow. So the result is wordier than C# but more informative.
We can now add the DefaultDataConnection connection string and test the worker role using the Verification instructions in the manual, and we are done with Exercise 2.
In Exercise 3 we publish the app to Azure, and I have good news (for myself, at least): there’s nothing more to write in this post! All the tasks in Exercise 3 are exactly the same as they would have been had we used C# alone.
So we see again that we can build and deploy Azure solutions with F# as well as we can with C#. Since our purpose has been to implement the WATK HOLs, we haven’t been trying especially hard to modify the solutions to take advantage of F#’s distinctive features. But I plan to address that in future posts. In the meantime I would welcome any suggestions you have for making the solutions better.