<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>voyce &#187; F#</title>
	<atom:link href="http://www.voyce.com/index.php/category/software-development/f/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.voyce.com</link>
	<description>Programming and debugging tidbits</description>
	<lastBuildDate>Sun, 15 Jan 2012 13:10:46 +0000</lastBuildDate>
	
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Looking back at 2011</title>
		<link>http://www.voyce.com/index.php/2012/01/04/looking-back-at-2011/</link>
		<comments>http://www.voyce.com/index.php/2012/01/04/looking-back-at-2011/#comments</comments>
		<pubDate>Wed, 04 Jan 2012 23:07:47 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[F#]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[2011]]></category>
		<category><![CDATA[kinect]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[WinDbg]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=1408</guid>
		<description><![CDATA[A quick look back at some of the stuff I've been doing this year.]]></description>
			<content:encoded><![CDATA[<p>Well, we&#8217;re a few days into 2012 and no armageddon yet, so it&#8217;s probably safe to take a quick glance back over our shoulder at some of the technical stuff that&#8217;s flashed past in the preceding 12 months.<br />
<span id="more-1408"></span></p>
<h2>Work: Using F# in anger</h2>
<p>During working hours (and sometimes beyond) I&#8217;ve been developing a large project using lots of F#, a little bit of C# and a bit too much XAML. It&#8217;s quite an interesting mix, with technologies that have a vastly different outlook on life: F# with it&#8217;s strong, compile-time type checking and XAML with its, err, not-so-strong type checking. In fact, XAML and WPF play so fast and loose with types, that errors in the binding mechanism only happen at run-time and are almost always eaten silently. As you can imagine, this makes for some fun debugging. All I can say is thank goodness for <a href="http://snoopwpf.codeplex.com/">Snoop</a>.</p>
<p>We have a quite a substantial amount of ViewModel code in F# (tens of thousands of lines), much of it using <code>Async</code> to allow us to create responsive UIs without requiring tons of boilerplate code. Generally it works nicely, but I do have some concerns about the amount of thread hopping going on, and how that will affect performance. Especially as we break things down into pretty small pieces of functionality, sometimes just a few simple operations, and each is run on the thread pool. I don&#8217;t have any concrete figures to go on here, and I&#8217;m hoping we don&#8217;t end up in a situation where we sacrifice user productivity for developer productivity. Time (and perfmon) will tell.</p>
<h3>Debugging</h3>
<p>I&#8217;ve done less hardcore WinDbg stuff this year. In fact, a couple of times I&#8217;ve been guilty of jumping in with the debugger where it probably would&#8217;ve been more effective to take a high-level look first. A case of having a debugger-shaped hammer, and everything looking like a nail.</p>
<h3>Moving to 64bit</h3>
<p>A very positive thing that happend this year was the move to 64-bit Windows 7 for development at work, meaning that Visual Studio actually stays up without crashing for more than an hour. Previously I&#8217;d been having a terrible time: the combination of a couple of large-ish F# projects and 32-bit XP caused frequent VS out-of-memory errors, which was very frustrating. Luckily the move to Windows 7 has resolved it, and I can even run more than a handful of apps at the same time; what a luxury. </p>
<h2>Home: iOS</h2>
<p>After a long day at work, I finally get to go home, put the kids to bed and then my feet up, and break-out Xcode for a bit of iOS hacking. This year I&#8217;ve been feeling like I&#8217;m finally getting my head around some of the things that are fundamental in iOS development; from Objective-C concepts like release/retain semantics to iOS specifics, view controllers, table views etc. Previously I&#8217;ve been guilty of some copy-and-paste coding, mostly because it&#8217;s pretty slow going getting up to speed with new tech (and the myriad iOS APIs) when you&#8217;re only getting to do it for a few hours while knackered after work. Well, that&#8217;s my excuse anyway.</p>
<p>I&#8217;ve been trying to finish off some of the apps that I&#8217;ve started, but not shipped. I tend to procrastinate a bit (massive understatement), and of course things aren&#8217;t helped by the development &#8216;fat tail&#8217;, where the last 20% &#8211; polishing and getting things &#8216;just right&#8217; &#8211; takes at least 80% of the time. My 2010 post on <a href="http://www.voyce.com/index.php/2010/04/10/creating-an-ipad-flip-clock-with-core-animation/">Core Animation flip clocks</a> continues to get a lot of traffic, and I finally bit the bullet and posted a (free!) <a href="http://itunes.com/apps/flipclock">app</a> that uses it and it&#8217;s getting a lot of downloads, which is nice. I also had a look at iAd, which I&#8217;ll reserve judgement on for the time being, at the minute it&#8217;s not looking particularly lucrative&#8230;</p>
<p>As well as iOS stuff, I also took a look at OpenGL. I tend to do this every now and again, each time dipping in a little further and understanding a bit more. This time round it was looking at shaders (in OpenGL ES 2.0) and integrating with <a href="http://www.voyce.com/index.php/2011/11/18/creating-a-physics-based-opengl-ios-app/">Bullet physics</a>. My learning was certainly helped by this excellent <a href="http://arcsynthesis.org/gltut/">Learning Modern 3D Graphics Programming</a> tutorial.</p>
<h3>Kinect and F#</h3>
<p>Also while at home I finally got around to setting-up by my Kinect to do a bit of F# hacking. In the end I didn&#8217;t produce <a href="http://www.voyce.com/index.php/2011/09/05/kinect-sdk-with-f/">very much</a>, but it was pretty good fun anyway.</p>
<h2>Bring on 2012</h2>
<p>So, to sum it up: more of the same really, I guess. Although this year there&#8217;s definitely been a bit more of a focus on UI development, in both WPF and iOS, which I&#8217;ve been enjoying. It does tend to feel a bit schizophrenic, switching between technologies and platforms at the end of the working day. It can be interesting to identify the common themes and significant differences in the two approaches to GUI development. </p>
<p>This year I&#8217;m hoping to make my blogging a bit more regular, but who knows if I&#8217;ll be able to stick to it&#8230; If there&#8217;s anything you&#8217;d particularly like me to focus on, feel free to leave a comment.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2012/01/04/looking-back-at-2011/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Kinect SDK with F#</title>
		<link>http://www.voyce.com/index.php/2011/09/05/kinect-sdk-with-f/</link>
		<comments>http://www.voyce.com/index.php/2011/09/05/kinect-sdk-with-f/#comments</comments>
		<pubDate>Mon, 05 Sep 2011 14:34:47 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[kinect]]></category>
		<category><![CDATA[wpf]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=1273</guid>
		<description><![CDATA[My first quick look at using the Kinect SDK with F#.]]></description>
			<content:encoded><![CDATA[<p><div id="attachment_1283" class="wp-caption alignleft" style="width: 210px"><a href="http://www.voyce.com/wp-content/uploads/2011/09/kinect.png"><img src="http://www.voyce.com/wp-content/uploads/2011/09/kinect.png" alt="Just what do you think you&#039;re doing, Dave?" title="kinect" width="200" height="200" class="size-full wp-image-1283" /></a><p class="wp-caption-text">Just what do you think you're doing, Dave?</p></div>I finally got around to taking a look at the <a href="http://research.microsoft.com/en-us/um/redmond/projects/kinectsdk/">Kinect SDK</a> the other day, partly because I was interested to see how the API looked from F#. Unfortunately getting it going turned out to be more of a pain than I was expecting.</p>
<p>The first bit was easy: I&#8217;m &#8220;lucky&#8221; enough to have one of the older Xboxes, which meant I&#8217;d had to get a Kinect with separate power, which is the one required by the SDK. Now all I needed was a Windows machine to develop on.<br />
<span id="more-1273"></span><br />
For all my Visual Studio stuff at home I use a virtual machine, and unfortunately I missed the point in the <a href="http://research.microsoft.com/en-us/um/redmond/projects/kinectsdk/docs/readme.htm">readme</a> about &#8220;Kinect for Windows applications cannot run in a virtual machine&#8221;. Doh. That would explain why, try as I might I couldn&#8217;t get <a href="http://www.virtualbox.org/">VirtualBox</a> to detect the device when I plugged it into the host. Whatever I did I ended up with a &#8216;resource is busy&#8217; error. </p>
<p>I even tried another VM, this time from VMWare. It got further, with the guest seeing the devices, but whenever I tried to run the sample apps the API initialisation call failed. Unfortunately the samples make a bit of a rookie mistake and don&#8217;t display the error code associated with the failure; the only way to get the underlying HRESULT is to debug the app. As it turned out the error was the catch-all <code>80080014</code>, which is attributed to various USB issues.</p>
<p>So, I finally relented and decided to once again set-up Bootcamp, which I&#8217;d stopped using a while back: why bother when VMs had done everything I needed? Again I was snookered, this time by the incompatibility of the <a href="http://en.wikipedia.org/wiki/Unified_Extensible_Firmware_Interface">EFI</a> firmware in my ageing MacBook with the Win7 x64 install disc (which I&#8217;d had to actually burn onto optical media &#8211; can&#8217;t remember the last time I burnt a real physical disk)!</p>
<p>Eventually, I got Win7 x86, Visual Studio and the Kinect SDK installed on the metal, plugged in the sensor and &#8211; whoa &#8211; the devices were recognised and the drivers installed and&#8230; the samples ran!</p>
<p>From this point doing some hacking was pretty straightforward. I set about creating a project that used the skeletal tracking ability from the SDK. The project needs to reference the <code>Microsoft.Research.Kinect</code> assembly, then we can open some namespaces and initialise the API:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">open</span> System
<span style="color: #06c; font-weight: bold;">open</span> Microsoft<span style="color: #000080;">.</span><span style="color: #505090;">Research</span><span style="color: #000080;">.</span><span style="color: #505090;">Kinect</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">let</span> nui <span style="color: #000080;">=</span> Nui<span style="color: #000080;">.</span><span style="color: #505090;">Runtime</span><span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
nui<span style="color: #000080;">.</span><span style="color: #505090;">Initialize</span><span style="color: #000080;">&#40;</span>Nui<span style="color: #000080;">.</span><span style="color: #505090;">RuntimeOptions</span><span style="color: #000080;">.</span><span style="color: #505090;">UseSkeletalTracking</span><span style="color: #000080;">&#41;</span></pre></div></div>

<p>The API uses .NET events to communicate back to the application that some form of data is available. Depending on the options that you specify at init time, any of the skeletal, depth frame or colour data will be returned in the event arguments. This seems like a good place to use F# Async&#8217;s event integration: Async.AwaitEvent. We can quite easily write some code that will create an Async task that will repeatedly listen for events:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">let</span> skeleton <span style="color: #000080;">&#40;</span>nui <span style="color: #000080;">:</span> Nui<span style="color: #000080;">.</span><span style="color: #505090;">Runtime</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
        <span style="color: #06c; font-weight: bold;">let</span> <span style="color: #06c; font-weight: bold;">rec</span> loop <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
            async <span style="color: #000080;">&#123;</span> 
                <span style="color: #06c; font-weight: bold;">let</span><span style="color: #000080;">!</span> args <span style="color: #000080;">=</span> Async<span style="color: #000080;">.</span><span style="color: #505090;">AwaitEvent</span> nui<span style="color: #000080;">.</span><span style="color: #505090;">SkeletonFrameReady</span>
                <span style="color: #060; font-style: italic;">// Do something with the args</span>
                <span style="color: #06c; font-weight: bold;">return</span><span style="color: #000080;">!</span> loop <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span> 
            <span style="color: #000080;">&#125;</span>
        loop <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
    <span style="color: #060; font-style: italic;">// Start the process of listening for events...</span>
    skeleton nui <span style="color: #000080;">|&gt;</span> Async<span style="color: #000080;">.</span><span style="color: #505090;">Start</span></pre></div></div>

<p>This seems to work nicely, although I&#8217;m not sure of the overhead involved, perhaps a solution involving Rx would be more appropriate. Anyway, let&#8217;s do something with the data we get in the event, like getting all the skeletons that are being tracked, and passing them to a <code>draw</code> function:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">                args<span style="color: #000080;">.</span><span style="color: #505090;">SkeletonFrame</span><span style="color: #000080;">.</span><span style="color: #505090;">Skeletons</span> 
                <span style="color: #000080;">|&gt;</span> Seq<span style="color: #000080;">.</span><span style="color: #505090;">filter</span> <span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">fun</span> s <span style="color: #000080;">-&gt;</span> s<span style="color: #000080;">.</span><span style="color: #505090;">TrackingState</span> <span style="color: #000080;">=</span> Nui<span style="color: #000080;">.</span><span style="color: #505090;">SkeletonTrackingState</span><span style="color: #000080;">.</span><span style="color: #505090;">Tracked</span><span style="color: #000080;">&#41;</span>
                <span style="color: #000080;">|&gt;</span> Seq<span style="color: #000080;">.</span><span style="color: #505090;">iter</span> draw</pre></div></div>

<p>All that&#8217;s left is doing something cool in <code>draw</code>! Oh, and setting up all the GUI stuff necessary to actually get some pixels on the screen. I went for the WPF approach (as the managed samples do), which involves creating a simple object tree to display a rectangle in a canvas in a grid in a window, and doing a bit of marshalling back from the thread pool (where our Async code runs) to the main GUI thread.</p>
<p>Here&#8217;s all the code for possibly the most tedious thing you could do with a Kinect! But hey, it&#8217;s a starting point, right? I&#8217;m sure at some point I&#8217;ll get around to doing something cooler than a couple of small red rectangles with it&#8230;</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">open</span> System
<span style="color: #06c; font-weight: bold;">open</span> System<span style="color: #000080;">.</span><span style="color: #505090;">Windows</span>
<span style="color: #06c; font-weight: bold;">open</span> Microsoft<span style="color: #000080;">.</span><span style="color: #505090;">Research</span><span style="color: #000080;">.</span><span style="color: #505090;">Kinect</span>
&nbsp;
<span style="color: #000080;">&#91;</span><span style="color: #000080;">&lt;</span>STAThread<span style="color: #000080;">&gt;</span><span style="color: #000080;">&#93;</span>
<span style="color: #06c; font-weight: bold;">do</span>
    <span style="color: #06c; font-weight: bold;">let</span> nui <span style="color: #000080;">=</span> Nui<span style="color: #000080;">.</span><span style="color: #505090;">Runtime</span><span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
    nui<span style="color: #000080;">.</span><span style="color: #505090;">Initialize</span><span style="color: #000080;">&#40;</span>Nui<span style="color: #000080;">.</span><span style="color: #505090;">RuntimeOptions</span><span style="color: #000080;">.</span><span style="color: #505090;">UseSkeletalTracking</span><span style="color: #000080;">&#41;</span>
&nbsp;
    <span style="color: #060; font-style: italic;">// lifted straight from the sample code</span>
    <span style="color: #06c; font-weight: bold;">let</span> getDisplayPosition w h <span style="color: #000080;">&#40;</span>joint <span style="color: #000080;">:</span> Nui<span style="color: #000080;">.</span><span style="color: #505090;">Joint</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
            <span style="color: #06c; font-weight: bold;">let</span> <span style="color: #06c; font-weight: bold;">mutable</span> depthX <span style="color: #000080;">=</span> 0<span style="color: #000080;">.</span>0f
            <span style="color: #06c; font-weight: bold;">let</span> <span style="color: #06c; font-weight: bold;">mutable</span> depthY <span style="color: #000080;">=</span> 0<span style="color: #000080;">.</span>0f
            nui<span style="color: #000080;">.</span><span style="color: #505090;">SkeletonEngine</span><span style="color: #000080;">.</span><span style="color: #505090;">SkeletonToDepthImage</span><span style="color: #000080;">&#40;</span>joint<span style="color: #000080;">.</span><span style="color: #505090;">Position</span>, <span style="color: #000080;">&amp;</span>depthX, <span style="color: #000080;">&amp;</span>depthY<span style="color: #000080;">&#41;</span>
            <span style="color: #06c; font-weight: bold;">let</span> depthX <span style="color: #000080;">=</span> depthX <span style="color: #000080;">*</span> 320<span style="color: #000080;">.</span>0f<span style="color: #000080;">;</span> <span style="color: #060; font-style: italic;">//convert to 320, 240 space</span>
            <span style="color: #06c; font-weight: bold;">let</span> depthY <span style="color: #000080;">=</span> depthY <span style="color: #000080;">*</span> 240<span style="color: #000080;">.</span>0f<span style="color: #000080;">;</span> <span style="color: #060; font-style: italic;">//convert to 320, 240 space</span>
            <span style="color: #06c; font-weight: bold;">let</span> <span style="color: #06c; font-weight: bold;">mutable</span> colorX <span style="color: #000080;">=</span> <span style="color: #c6c;">0</span>
            <span style="color: #06c; font-weight: bold;">let</span> <span style="color: #06c; font-weight: bold;">mutable</span> colorY <span style="color: #000080;">=</span> <span style="color: #c6c;">0</span>
            <span style="color: #06c; font-weight: bold;">let</span> iv <span style="color: #000080;">=</span> <span style="color: #06c; font-weight: bold;">new</span> Nui<span style="color: #000080;">.</span><span style="color: #505090;">ImageViewArea</span><span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
            <span style="color: #060; font-style: italic;">// only ImageResolution.Resolution640x480 is supported at this point</span>
            nui<span style="color: #000080;">.</span><span style="color: #505090;">NuiCamera</span><span style="color: #000080;">.</span><span style="color: #505090;">GetColorPixelCoordinatesFromDepthPixel</span><span style="color: #000080;">&#40;</span>Nui<span style="color: #000080;">.</span><span style="color: #505090;">ImageResolution</span><span style="color: #000080;">.</span><span style="color: #505090;">Resolution640x480</span>, iv, 
                <span style="color: #000080;">&#40;</span>int<span style="color: #000080;">&#41;</span>depthX, <span style="color: #000080;">&#40;</span>int<span style="color: #000080;">&#41;</span>depthY, 0s, <span style="color: #000080;">&amp;</span>colorX, <span style="color: #000080;">&amp;</span>colorY<span style="color: #000080;">&#41;</span>
&nbsp;
            <span style="color: #060; font-style: italic;">// map back to visible area</span>
            <span style="color: #06c; font-weight: bold;">new</span> Point<span style="color: #000080;">&#40;</span><span style="color: #000080;">&#40;</span>w <span style="color: #000080;">*</span> <span style="color: #000080;">&#40;</span>float<span style="color: #000080;">&#41;</span>colorX <span style="color: #000080;">/</span> 640<span style="color: #000080;">.</span><span style="color: #000080;">&#41;</span>, <span style="color: #000080;">&#40;</span>h <span style="color: #000080;">*</span> <span style="color: #000080;">&#40;</span>float<span style="color: #000080;">&#41;</span>colorY <span style="color: #000080;">/</span> 480<span style="color: #000080;">.</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span>
&nbsp;
    <span style="color: #060; font-style: italic;">// Set-up the WPF window and its contents</span>
    <span style="color: #06c; font-weight: bold;">let</span> width <span style="color: #000080;">=</span> 1024<span style="color: #000080;">.</span>
    <span style="color: #06c; font-weight: bold;">let</span> height <span style="color: #000080;">=</span> 768<span style="color: #000080;">.</span>
    <span style="color: #06c; font-weight: bold;">let</span> w <span style="color: #000080;">=</span> Window<span style="color: #000080;">&#40;</span>Width<span style="color: #000080;">=</span>width, Height<span style="color: #000080;">=</span>height<span style="color: #000080;">&#41;</span>
    <span style="color: #06c; font-weight: bold;">let</span> g <span style="color: #000080;">=</span> Controls<span style="color: #000080;">.</span><span style="color: #505090;">Grid</span><span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
    <span style="color: #06c; font-weight: bold;">let</span> c <span style="color: #000080;">=</span> Controls<span style="color: #000080;">.</span><span style="color: #505090;">Canvas</span><span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
    <span style="color: #06c; font-weight: bold;">let</span> hd <span style="color: #000080;">=</span> Shapes<span style="color: #000080;">.</span><span style="color: #505090;">Rectangle</span><span style="color: #000080;">&#40;</span>Fill<span style="color: #000080;">=</span>Media<span style="color: #000080;">.</span><span style="color: #505090;">Brushes</span><span style="color: #000080;">.</span><span style="color: #505090;">Red</span>, Width<span style="color: #000080;">=</span>10<span style="color: #000080;">.</span>, Height<span style="color: #000080;">=</span>10<span style="color: #000080;">.</span><span style="color: #000080;">&#41;</span>
    ignore <span style="color: #000080;">&lt;|</span> c<span style="color: #000080;">.</span><span style="color: #505090;">Children</span><span style="color: #000080;">.</span><span style="color: #505090;">Add</span> hd
    ignore <span style="color: #000080;">&lt;|</span> g<span style="color: #000080;">.</span><span style="color: #505090;">Children</span><span style="color: #000080;">.</span><span style="color: #505090;">Add</span> c
    w<span style="color: #000080;">.</span><span style="color: #505090;">Content</span> <span style="color: #000080;">&lt;-</span> g
&nbsp;
    <span style="color: #060; font-style: italic;">// We simple move the rectangle to where the head is</span>
    <span style="color: #06c; font-weight: bold;">let</span> draw <span style="color: #000080;">&#40;</span>s <span style="color: #000080;">:</span> Nui<span style="color: #000080;">.</span><span style="color: #505090;">SkeletonData</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
        <span style="color: #06c; font-weight: bold;">let</span> point <span style="color: #000080;">=</span> getDisplayPosition width height s<span style="color: #000080;">.</span><span style="color: #505090;">Joints</span><span style="color: #000080;">.</span><span style="color: #000080;">&#91;</span>Nui<span style="color: #000080;">.</span><span style="color: #505090;">JointID</span><span style="color: #000080;">.</span><span style="color: #505090;">Head</span><span style="color: #000080;">&#93;</span>
        ignore <span style="color: #000080;">&lt;|</span> w<span style="color: #000080;">.</span><span style="color: #505090;">Dispatcher</span><span style="color: #000080;">.</span><span style="color: #505090;">BeginInvoke</span><span style="color: #000080;">&#40;</span>Threading<span style="color: #000080;">.</span><span style="color: #505090;">DispatcherPriority</span><span style="color: #000080;">.</span><span style="color: #505090;">Normal</span>, Action<span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">fun</span> <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">-&gt;</span>    
            hd<span style="color: #000080;">.</span><span style="color: #505090;">SetValue</span><span style="color: #000080;">&#40;</span>Controls<span style="color: #000080;">.</span><span style="color: #505090;">Canvas</span><span style="color: #000080;">.</span><span style="color: #505090;">TopProperty</span>, point<span style="color: #000080;">.</span><span style="color: #505090;">Y</span><span style="color: #000080;">&#41;</span>
            hd<span style="color: #000080;">.</span><span style="color: #505090;">SetValue</span><span style="color: #000080;">&#40;</span>Controls<span style="color: #000080;">.</span><span style="color: #505090;">Canvas</span><span style="color: #000080;">.</span><span style="color: #505090;">LeftProperty</span>, point<span style="color: #000080;">.</span><span style="color: #505090;">X</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span>
&nbsp;
    <span style="color: #06c; font-weight: bold;">let</span> skeleton <span style="color: #000080;">&#40;</span>nui <span style="color: #000080;">:</span> Nui<span style="color: #000080;">.</span><span style="color: #505090;">Runtime</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
        <span style="color: #06c; font-weight: bold;">let</span> <span style="color: #06c; font-weight: bold;">rec</span> loop <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
            async <span style="color: #000080;">&#123;</span> 
                <span style="color: #06c; font-weight: bold;">let</span><span style="color: #000080;">!</span> args <span style="color: #000080;">=</span> Async<span style="color: #000080;">.</span><span style="color: #505090;">AwaitEvent</span> nui<span style="color: #000080;">.</span><span style="color: #505090;">SkeletonFrameReady</span>
                args<span style="color: #000080;">.</span><span style="color: #505090;">SkeletonFrame</span><span style="color: #000080;">.</span><span style="color: #505090;">Skeletons</span> 
                <span style="color: #000080;">|&gt;</span> Seq<span style="color: #000080;">.</span><span style="color: #505090;">filter</span> <span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">fun</span> s <span style="color: #000080;">-&gt;</span> s<span style="color: #000080;">.</span><span style="color: #505090;">TrackingState</span> <span style="color: #000080;">=</span> Nui<span style="color: #000080;">.</span><span style="color: #505090;">SkeletonTrackingState</span><span style="color: #000080;">.</span><span style="color: #505090;">Tracked</span><span style="color: #000080;">&#41;</span>
                <span style="color: #000080;">|&gt;</span> Seq<span style="color: #000080;">.</span><span style="color: #505090;">iter</span> draw
                <span style="color: #06c; font-weight: bold;">return</span><span style="color: #000080;">!</span> loop <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span> 
            <span style="color: #000080;">&#125;</span>
        loop <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
&nbsp;
    skeleton nui <span style="color: #000080;">|&gt;</span> Async<span style="color: #000080;">.</span><span style="color: #505090;">Start</span>
&nbsp;
    <span style="color: #06c; font-weight: bold;">let</span> a <span style="color: #000080;">=</span> System<span style="color: #000080;">.</span><span style="color: #505090;">Windows</span><span style="color: #000080;">.</span><span style="color: #505090;">Application</span><span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
    ignore <span style="color: #000080;">&lt;|</span> a<span style="color: #000080;">.</span><span style="color: #505090;">Run</span><span style="color: #000080;">&#40;</span>w<span style="color: #000080;">&#41;</span>
&nbsp;
    nui<span style="color: #000080;">.</span><span style="color: #505090;">Uninitialize</span><span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span></pre></div></div>

<p>The moral of the story? Don&#8217;t be like me, and make sure you actually read the FAQing readme, then maybe you&#8217;ll spend more time doing a decent demo and less time plugging and unplugging your Kinect!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2011/09/05/kinect-sdk-with-f/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>F# Async: Plays well with others?</title>
		<link>http://www.voyce.com/index.php/2011/05/27/fsharp-async-plays-well-with-others/</link>
		<comments>http://www.voyce.com/index.php/2011/05/27/fsharp-async-plays-well-with-others/#comments</comments>
		<pubDate>Fri, 27 May 2011 22:55:46 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[async]]></category>
		<category><![CDATA[parallel]]></category>
		<category><![CDATA[threading]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=1208</guid>
		<description><![CDATA[Async is a powerful way of getting parallelism in your F# code, just be careful what you call within your Async workflows.]]></description>
			<content:encoded><![CDATA[<p>OK, quick <a href="http://msdn.microsoft.com/en-us/library/dd233250.aspx">Async</a> pop quiz: How long does the <code>run</code> function below take to execute?</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">module</span> Test <span style="color: #000080;">=</span> 
    <span style="color: #06c; font-weight: bold;">let</span> work i <span style="color: #000080;">=</span> 
        async <span style="color: #000080;">&#123;</span> 
            System<span style="color: #000080;">.</span><span style="color: #505090;">Threading</span><span style="color: #000080;">.</span><span style="color: #505090;">Thread</span><span style="color: #000080;">.</span><span style="color: #505090;">Sleep</span><span style="color: #000080;">&#40;</span><span style="color: #c6c;">500</span><span style="color: #000080;">&#41;</span> 
            <span style="color: #06c; font-weight: bold;">return</span> i<span style="color: #000080;">+</span><span style="color: #c6c;">1</span> 
        <span style="color: #000080;">&#125;</span>
    <span style="color: #06c; font-weight: bold;">let</span> run <span style="color: #06c; font-weight: bold;">_</span> <span style="color: #000080;">=</span> 
        <span style="color: #000080;">&#91;</span>1<span style="color: #000080;">..</span>1000<span style="color: #000080;">&#93;</span> <span style="color: #000080;">|&gt;</span> List<span style="color: #000080;">.</span><span style="color: #505090;">map</span> work 
        <span style="color: #000080;">|&gt;</span> Async<span style="color: #000080;">.</span><span style="color: #505090;">Parallel</span> 
        <span style="color: #000080;">|&gt;</span> Async<span style="color: #000080;">.</span><span style="color: #505090;">RunSynchronously</span></pre></div></div>

<p>(Waits for people to start FSI and paste in the code&#8230;)</p>
<p>My guess would&#8217;ve been something just over 500ms; each of the 1000 async tasks would surely sleep in parallel, and then the operation itself is trivial. The additional elapsed time would be dominated by the overhead of thread management, and depend on the number of threads that can physically run in parallel (I&#8217;m using an 8-core machine). But still, something close to 500ms&#8230;</p>
<p>The actual result? 28000ms. Yes, you read that right: 28 seconds. What on earth did we do wrong?<br />
<span id="more-1208"></span><br />
Surely it can&#8217;t be that <a href="http://msdn.microsoft.com/en-us/library/d00bd51t.aspx">Sleep</a>, right? I mean, each task is going to run on the thread pool anyway, so what difference would that make? Well, that *is* exactly the problem. It turns out that you can&#8217;t mix &#8220;vanilla&#8221; threading calls with <code>Async</code> API ones, because Async works in a completely different and incompatible way. If we use raw threading functions like <code>Sleep</code>, the async framework has no way of knowing if we&#8217;re doing anything useful. It eventually ends up causing .NET thread pool starvation, as we&#8217;re essentially grabbing and holding each thread in a way that doesn&#8217;t cooperate with anything else. New threads will spin-up to compensate and we&#8217;ll end up getting additional memory usage as well as worse performance. </p>
<p><div id="attachment_1232" class="wp-caption alignleft" style="width: 81px"><a href="http://www.voyce.com/wp-content/uploads/2011/05/threads_raw.png"><img src="http://www.voyce.com/wp-content/uploads/2011/05/threads_raw-71x300.png" alt="Nasty" title="threads_raw" width="71" height="300" class="size-medium wp-image-1232" /></a><p class="wp-caption-text">Nasty</p></div> This is a very rough impression of how things look if you use non-async aware blocking. Vertical lines represent threads in the thread pool, artificially restricted to 3 for diagrammatic purposes. Notice how each of the &#8216;blocks of work&#8217; are large, and the opportunities to spread the work amongst threads is small. As a result, total elapsed time is large.<br />
<br clear="all"/></p>
<p>Instead Async uses what&#8217;s called <a href="http://en.wikipedia.org/wiki/Continuation-passing_style">continuation passing style</a>, a technique favoured by the functional programming community, that also happens to map quite nicely to features in the CLR, including the thread pool, tail calls and garbage collection. It has the rather nice feature that it never blocks an OS thread (unless it&#8217;s busy actually executing). Instead it queues a function (a continuation) to be called at some later point. </p>
<p><div id="attachment_1233" class="wp-caption alignright" style="width: 193px"><a href="http://www.voyce.com/wp-content/uploads/2011/05/threads_async.png"><img src="http://www.voyce.com/wp-content/uploads/2011/05/threads_async-183x300.png" alt="Nice" title="threads_async" width="183" height="300" class="size-medium wp-image-1233" /></a><p class="wp-caption-text">Nice</p></div>Here the blocks are broken into a small amount of initial work to create and schedule the event, and then a further small amount to execute the continuation. In the meantime other code can be run (in this case, other instances of the same task), and we get good usage of the thread pool.<br clear="all"/></p>
<p>For all the gory details and full Async semantics, I suggest you read the <a href="http://research.microsoft.com/pubs/147194/async-padl-revised-v2.pdf">paper</a> from Microsoft Research. Tucked away in there you&#8217;ll see that they do mention this restriction: </p>
<blockquote><p> The key facet of an asynchronous I/O primitive is that it does not block an OS thread while executing, but instead schedules the continuation of the asynchronous computation as a callback in response to an event.
</p></blockquote>
<p>So how do we &#8220;fix&#8221; our example? Simple: we replace the non-CPS-friendly explicit Sleep, with an Async-native Sleep.</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">module</span> Test <span style="color: #000080;">=</span> 
    <span style="color: #06c; font-weight: bold;">let</span> work i <span style="color: #000080;">=</span> 
        async <span style="color: #000080;">&#123;</span> 
            <span style="color: #06c; font-weight: bold;">do</span><span style="color: #000080;">!</span> Async<span style="color: #000080;">.</span><span style="color: #505090;">Sleep</span><span style="color: #000080;">&#40;</span><span style="color: #c6c;">500</span><span style="color: #000080;">&#41;</span> 
            <span style="color: #06c; font-weight: bold;">return</span> i<span style="color: #000080;">+</span><span style="color: #c6c;">1</span> 
        <span style="color: #000080;">&#125;</span>
    <span style="color: #06c; font-weight: bold;">let</span> run <span style="color: #06c; font-weight: bold;">_</span> <span style="color: #000080;">=</span> 
        <span style="color: #000080;">&#91;</span>1<span style="color: #000080;">..</span>1000<span style="color: #000080;">&#93;</span> <span style="color: #000080;">|&gt;</span> List<span style="color: #000080;">.</span><span style="color: #505090;">map</span> work 
        <span style="color: #000080;">|&gt;</span> Async<span style="color: #000080;">.</span><span style="color: #505090;">Parallel</span> 
        <span style="color: #000080;">|&gt;</span> Async<span style="color: #000080;">.</span><span style="color: #505090;">RunSynchronously</span></pre></div></div>

<p>The result now: 558ms. Much more like it! </p>
<p>What happens is that the <code>Async.Sleep</code> call is converted into an event that is fired after 500ms to continue the execution, i.e. actually perform the addition. In the meantime, each of the other instances of the workflow get a chance to run, and we get real parallelism.   </p>
<p>In this case it might look screamingly obvious, but be aware if you&#8217;re doing something such as calling into a third-party, legacy, or otherwise non-Async-aware code, it could cause your otherwise highly parallel code to choke. You&#8217;ll have to wrap it up in order to make it play nicely with Async and make sure you get the full benefit of this powerful F# feature.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2011/05/27/fsharp-async-plays-well-with-others/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mixing it up: when F# meets C#</title>
		<link>http://www.voyce.com/index.php/2011/05/09/mixing-it-up-when-f-meets-c/</link>
		<comments>http://www.voyce.com/index.php/2011/05/09/mixing-it-up-when-f-meets-c/#comments</comments>
		<pubDate>Mon, 09 May 2011 22:18:26 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[CLR]]></category>
		<category><![CDATA[IL]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=1146</guid>
		<description><![CDATA[How does it look when F# meets C#?]]></description>
			<content:encoded><![CDATA[<p><div class="wp-caption alignleft" style="width: 130px"><a href="http://www.flickr.com/photos/ianvoyce/5676819517/"><img alt="Simples?" src="http://farm6.static.flickr.com/5189/5676819517_e93bee2c41_m.jpg" title="meerkat" width="120" height="180" /></a><p class="wp-caption-text">Simples?</p></div>If it were a perfect world, we&#8217;d all exist in a happy little bubble of our favourite programming language and you&#8217;d never have to worry about the nasty details of interacting with something written by &#8211; gasp &#8211; someone else in a &#8211; double-gasp &#8211; different language. But unfortunately that&#8217;s precisely what we have to do all the time. And that means that one day all of your fancy-pants algorithmic, highly parallel, functionally pure F# code is going to meet the world of &#8220;enterprise&#8221; C# development head-on.</p>
<p>Of course the idiomatic way to avoid problems at the boundary between your F# code and the outside world is to ensure that you only expose a small set of compatible types. This works pretty well if your clients are also .NET languages. For instance you can do things like exposing your collections as <code>seq<T></code>, rather than say, a native F# <code>list</code>, and this will mean your collections can be consumed as <code>IEnumerable<T></code>. The only problem is it means you&#8217;ve got the added burden of maintaining this mapping layer, because you&#8217;ll no doubt want to use the F# &#8220;native&#8221; types internally.</p>
<p>So, what options do we have if some of our F# types happen to leak into our public API? Luckily, lots. Let&#8217;s take a look at how some of the common F# constructs can be called from C#.<br />
<span id="more-1146"></span></p>
<h3>Unions</h3>
<p>I talked about the power of discriminated unions a while back, so how do they map to C#? Interestingly the F# compiler generates a very simple OO type hierarchy, with an abstract base class that each of the cases derive from. This will mean that your calling code will need  to use some casting, but don&#8217;t worry, you&#8217;re not back in the hell of runtime typing; there are a set of methods on the type that you can use to identify the case before you do the cast, so at least you get some compile time sanity checking.</p>
<p>Here&#8217;s a simple discriminated union that we&#8217;ll be using as an example:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">type</span> TestDU <span style="color: #000080;">=</span>
        <span style="color: #000080;">|</span> One <span style="color: #06c; font-weight: bold;">of</span> int <span style="color: #000080;">*</span> int
        <span style="color: #000080;">|</span> Two <span style="color: #06c; font-weight: bold;">of</span> string
        <span style="color: #000080;">|</span> Three</pre></div></div>

<p>If we wanted to use this type in F#, we&#8217;d do so like this:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #060; font-style: italic;">// A function 'f' that takes an instance 't' of our union type</span>
    <span style="color: #06c; font-weight: bold;">let</span> f t <span style="color: #000080;">=</span> <span style="color: #06c; font-weight: bold;">match</span> t <span style="color: #06c; font-weight: bold;">with</span> One <span style="color: #000080;">&#40;</span>a,b<span style="color: #000080;">&#41;</span> <span style="color: #000080;">-&gt;</span> printf <span style="color: #008080;">&quot;Got One&quot;</span> <span style="color: #000080;">|</span> <span style="color: #06c; font-weight: bold;">_</span> <span style="color: #000080;">-&gt;</span> <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
&nbsp;
    <span style="color: #060; font-style: italic;">// Apply our function with a particular TestDU union case</span>
    <span style="color: #06c; font-weight: bold;">let</span> <span style="color: #06c; font-weight: bold;">_</span> <span style="color: #000080;">=</span> f <span style="color: #000080;">&lt;|</span> Two <span style="color: #008080;">&quot;foo&quot;</span></pre></div></div>

<p>That&#8217;s pretty natural, as you&#8217;d expect. If we exposed the function <code>f</code> to C#, it looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">void</span> Module1.<span style="color: #0000FF;">f</span><span style="color: #000000;">&#40;</span>Module1.<span style="color: #0000FF;">TestDU</span> t<span style="color: #000000;">&#41;</span></pre></div></div>

<p>This means we have to create an instance of the <code>TestDU</code> type, but we&#8217;ll quickly discover it&#8217;s abstract. As I mentioned before, the F# compiler has generated a very simple class hierarchy, with the union cases being subtypes of <code>TestDU</code>, implemented as <a href="http://msdn.microsoft.com/en-us/library/ms173120.aspx">nested types</a> (which are used quite extensively by the F# compiler). But if we try and instantiate one of these subtypes&#8230;?<br />
<div id="attachment_1171" class="wp-caption alignleft" style="width: 427px"><a href="http://www.voyce.com/wp-content/uploads/2011/05/testdu_noctors.png"><img src="http://www.voyce.com/wp-content/uploads/2011/05/testdu_noctors.png" alt="The union case types have no constructors." title="testdu_noctors" width="417" height="106" class="size-full wp-image-1171" /></a><p class="wp-caption-text">The union case types have no constructors.</p></div><br />
Ouch: &#8216;No constructors defined&#8217;. Luckily, instead there are helper functions on the base class that will create instances for us, at least for those cases with arguments. The functions are prefixed with &#8216;New&#8217;, e.g.:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    var one <span style="color: #008000;">=</span> Module1.<span style="color: #0000FF;">TestDU</span>.<span style="color: #0000FF;">NewOne</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">1</span>, <span style="color: #FF0000;">2</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    var two <span style="color: #008000;">=</span> Module1.<span style="color: #0000FF;">TestDU</span>.<span style="color: #0000FF;">NewTwo</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;foo&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>And slightly oddly, the parameterless cases (<code>Three</code> in our example) use a property on the base class instead:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    var three <span style="color: #008000;">=</span> Module1.<span style="color: #0000FF;">TestDU</span>.<span style="color: #0000FF;">Three</span><span style="color: #008000;">;</span></pre></div></div>

<p>So now we can create instances of the union type to pass to the F# function.</p>
<p>But what if we&#8217;re returned one instead? It will be of type <code>TestDU</code>, so how do we know what case it actually is? And how do we get to the parameters? Well, as we know it&#8217;s going to be one of the subtypes, we could use the C# &#8216;is&#8217; operator to determine its identity, but the base class also provides helper methods to do it for us, prefixed with <code>Is</code>, e.g.:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>two.<span style="color: #0000FF;">IsTwo</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        var x <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span>two <span style="color: #0600FF;">as</span> Module1.<span style="color: #0000FF;">TestDU</span>.<span style="color: #0000FF;">Two</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Item</span><span style="color: #008000;">;</span>
        <span style="color: #008080; font-style: italic;">// Do something with x</span>
    <span style="color: #000000;">&#125;</span></pre></div></div>

<p>As you can see, <code>Item</code> contains the case value. For tupled types this becomes <code>Item1</code>, <code>Item2</code> etc.</p>
<h3>Records</h3>
<p>Records are immutable types that contain fields, they tend to be used quite a lot in F# code, and luckily using them from C# is very straightforward. The only thing to remember is that they&#8217;re only constructor is the one taking all of the field values (because they&#8217;re immutable), e.g.:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">type</span> TestRecord <span style="color: #000080;">=</span>
        <span style="color: #000080;">&#123;</span>
        field1 <span style="color: #000080;">:</span> int
        field2 <span style="color: #000080;">:</span> string
        <span style="color: #000080;">&#125;</span></pre></div></div>

<p>Can be instantiated like this in C#:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    var r <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Module1.<span style="color: #0000FF;">TestRecord</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">1</span>, <span style="color: #666666;">&quot;foo&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<h3>Functions</h3>
<p>It&#8217;s usual in F# to use curried functions. That is, functions that can be applied one argument at a time, returning a partially applied function. It turns out that the compiler maps this type of function (when directly exposed, as a public function on a module, say) into its tupled equivalent, which makes them easily callable directly from C#. For instance:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">let</span> <span style="color: #06c; font-weight: bold;">public</span> adder a b <span style="color: #000080;">=</span> a <span style="color: #000080;">+</span> b</pre></div></div>

<p>Has a native F# signature of <code>int -> int -> int</code>, but results in a generated CIL function taking a tuple of two ints, with signature more like <code>int * int -> int</code>.</p>
<p>But there are more complicated cases; F# functions can take functions and return them. When we&#8217;re dealing with functions in a first-class way like this, we can use the generic <code>Microsoft.FSharp.Core.FSharpFunc</code> type. For example:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">let</span> <span style="color: #06c; font-weight: bold;">public</span> adder a b <span style="color: #000080;">=</span> a <span style="color: #000080;">+</span> b
    <span style="color: #06c; font-weight: bold;">let</span> <span style="color: #06c; font-weight: bold;">public</span> addOne <span style="color: #000080;">=</span> adder <span style="color: #c6c;">1</span></pre></div></div>

<p>Where <code>addOne</code> is a function that returns a partially applied function. Calling it from F# is a breeze:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">let</span> x <span style="color: #000080;">=</span> addOne <span style="color: #c6c;">100</span></pre></div></div>

<p>But from C# it&#8217;s a bit trickier. The function returns an FSharpFunc, that we then need to apply with <code>Invoke</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    Microsoft.<span style="color: #0000FF;">FSharp</span>.<span style="color: #0000FF;">Core</span>.<span style="color: #0000FF;">FSharpFunc</span><span style="color: #008000;">&lt;</span><span style="color: #FF0000;">int</span>,<span style="color: #FF0000;">int</span><span style="color: #008000;">&gt;</span> f <span style="color: #008000;">=</span> Module1.<span style="color: #0000FF;">addOne</span><span style="color: #008000;">;</span>
    var x <span style="color: #008000;">=</span> f.<span style="color: #0000FF;">Invoke</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">100</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Although obviously you can combine this into a single line, and remove some of the type signatures (which I tend to do as much as possible using <code>var</code> when writing C# code):</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    var x <span style="color: #008000;">=</span> Module1.<span style="color: #0000FF;">addOne</span>.<span style="color: #0000FF;">Invoke</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">100</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Things get even nastier if you happen to expose an F# function that takes a function. For example, a function that takes another function and applies it to two arguments:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">let</span> apply op a b <span style="color: #000080;">=</span> op a b</pre></div></div>

<p>In F# interactive we can see that this has the following, nicely generalised type signature:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">val</span> apply <span style="color: #000080;">:</span> <span style="color: #000080;">&#40;</span><span style="color: #000080;">'</span>a <span style="color: #000080;">-&gt;</span> <span style="color: #000080;">'</span>b <span style="color: #000080;">-&gt;</span> <span style="color: #000080;">'</span>c<span style="color: #000080;">&#41;</span> <span style="color: #000080;">-&gt;</span> <span style="color: #000080;">'</span>a <span style="color: #000080;">-&gt;</span> <span style="color: #000080;">'</span>b <span style="color: #000080;">-&gt;</span> <span style="color: #000080;">'</span>c</pre></div></div>

<p>i.e. it&#8217;s a function that takes as its first argument a function that takes an &#8216;a and a &#8216;b and returns a &#8216;c, it also accepts the &#8216;a and &#8216;b to pass to this function, and returns the &#8216;c result. Clear as. We may well want to create a version of this that uses the integer operator +, which is trivial from F#:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">let</span> add a b <span style="color: #000080;">=</span> apply <span style="color: #000080;">&#40;</span><span style="color: #000080;">+</span><span style="color: #000080;">&#41;</span> a b</pre></div></div>

<p>So how does it look if we try and do that from C#? In a word: messy. We have to use the <code>Microsoft.FSharp.Core.FuncConvert.ToFSharpFunc</code> helper functions, along with the .NET framework <code>Converter</code> as a way of specifying a generic, value-returning function.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    <span style="color: #0600FF;">using</span> <span style="color: #008080;">Microsoft.FSharp.Core</span><span style="color: #008000;">;</span>
...
    <span style="color: #0000FF;">var</span> op <span style="color: #008000;">=</span> FuncConvert.<span style="color: #0000FF;">ToFSharpFunc</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> Converter<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">int</span>, FSharpFunc<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">int</span>, <span style="color: #FF0000;">int</span><span style="color: #008000;">&gt;&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>aa<span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">return</span> FuncConvert.<span style="color: #0000FF;">ToFSharpFunc</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> Converter<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">int</span>, <span style="color: #FF0000;">int</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>bb<span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #008080; font-style: italic;">// The 'meat' of the function. Hmmm...</span>
                <span style="color: #0600FF;">return</span> aa <span style="color: #008000;">+</span> bb<span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    var zz <span style="color: #008000;">=</span> Module1.<span style="color: #0000FF;">apply</span><span style="color: #000000;">&#40;</span>op, <span style="color: #FF0000;">1</span>, <span style="color: #FF0000;">2</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Whoa. That&#8217;s enough for now. As you can see, the various different ways of interoperating between F# and C# range from the neat to the nasty. The trick is definitely to pick your battles. Think carefully about what you need to expose and remember it&#8217;s probably best not to cross the beams if you can avoid it. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2011/05/09/mixing-it-up-when-f-meets-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Not dead, just busy</title>
		<link>http://www.voyce.com/index.php/2011/02/22/not-dead-just-busy/</link>
		<comments>http://www.voyce.com/index.php/2011/02/22/not-dead-just-busy/#comments</comments>
		<pubDate>Tue, 22 Feb 2011 21:59:24 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[F#]]></category>
		<category><![CDATA[iOS]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=1148</guid>
		<description><![CDATA[Where've I been...?]]></description>
			<content:encoded><![CDATA[<p>Well, the title says it all really. I just wanted to let everyone know that I&#8217;m not dead &#8211; despite what you may be thinking based on my lack of blog output &#8211; it&#8217;s just that I&#8217;ve been insanely busy on a project in the day job. Yep, it&#8217;s that old excuse of real paying work getting in the way of the fun stuff again.</p>
<p>Hopefully soon I&#8217;ll manage to post some new stuff, possibly more &#8216;transitioning to F#&#8217; posts and bit more iOS development malarkey. In the meantime, keep on keeping on.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2011/02/22/not-dead-just-busy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Beginning F#: Positive Discrimination</title>
		<link>http://www.voyce.com/index.php/2010/11/29/fsharp-positive-discrimination/</link>
		<comments>http://www.voyce.com/index.php/2010/11/29/fsharp-positive-discrimination/#comments</comments>
		<pubDate>Mon, 29 Nov 2010 23:24:46 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Finance]]></category>
		<category><![CDATA[functional programming]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=1068</guid>
		<description><![CDATA[Discriminated unions for the rest of us.]]></description>
			<content:encoded><![CDATA[<p>(or &#8220;Discriminated unions for dummies like me&#8221;, or &#8220;Tagged unions for the rest of us&#8221;)</p>
<p>Discriminated unions are one of those things in the lexicon of functional programming that can often sound baffling to &#8220;outsiders&#8221;; it&#8217;s almost up there with monads and currying. But in practice they&#8217;re simple and incredibly useful. I thought I&#8217;d try and show a concrete example of where they can be used in a way which is more powerful and robust than the equivalent OO approach.<br />
<span id="more-1068"></span></p>
<h3>The usual suspects</h3>
<p>When people first start looking at functional programming, they often come across examples that implement a compiler, and this is their first exposure to discriminated unions. Unfortunately these examples tend to use complex recursive discriminated unions to represent the language syntax tree, which can be a bit of turn-off for anyone who&#8217;s not a language geek.</p>
<h3>A problem</h3>
<p>The way I like to think of DUs is a means of easily and precisely specifying a set of types that we&#8217;re expecting to work with. </p>
<p>What do I mean by this? Well, imagine you&#8217;re writing some code that can work on various different types, and you need to identify some common aspect to identify them. For example, you&#8217;re valuing different financial product types: swaps, swaptions, caps and floors. Although each of these trade types would be represented differently, you may want to perform the same operation across all of them.</p>
<h3>The OO approach</h3>
<p>The normal OO approach would be to use an interface; implemented by all of the types and consumed by our method. For instance:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #FF0000;">class</span> Swap <span style="color: #008000;">:</span> <span style="color: #0600FF;">public</span> IValuable <span style="color: #000000;">&#123;</span> ... <span style="color: #000000;">&#125;</span>
<span style="color: #FF0000;">class</span> Swaption <span style="color: #008000;">:</span> <span style="color: #0600FF;">public</span> IValuable <span style="color: #000000;">&#123;</span> ... <span style="color: #000000;">&#125;</span>
...
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">double</span> ValueTrades<span style="color: #000000;">&#40;</span>IValuable<span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> trades<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span> ... <span style="color: #000000;">&#125;</span></pre></div></div>

<p>But this isn&#8217;t particularly elegant or easy. For a start it requires that the type implement the interface &#8211; what if you&#8217;re working with externally provided types that can&#8217;t be changed? The other thing is that interfaces tend to give you a false sense of security about type safety. Given that we know there&#8217;s an object implementing the interface, I&#8217;ve all too often seen OO code taking an interface parameter then immediately type-casting it to another interface that the underlying object is expected to support. Run-time typing failures FTL.     </p>
<h3>The union</h3>
<p>So how could we implement this using discriminated unions instead?</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">type</span> Trade <span style="color: #000080;">=</span> 
    <span style="color: #000080;">|</span> SwapTrade <span style="color: #06c; font-weight: bold;">of</span> Swap
    <span style="color: #000080;">|</span> SwaptionTrade <span style="color: #06c; font-weight: bold;">of</span> Swaption</pre></div></div>

<p>What we&#8217;ve done is create a new type that consists of exactly one of its possible cases. We identify each case with a tag (in fact, these types are often called tagged unions) called SwapTrade and SwaptionTrade and separate them with the bar &#8216;|&#8217;. </p>
<p>Easy, isn&#8217;t it? But, err, how do we get to the actual thing we want? Well that&#8217;s where another functional programming staple steps in: pattern matching. We can add some code that will match against the possible union cases and allow us to get at the type itself:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">let</span> valueTrades <span style="color: #000080;">&#40;</span>trades <span style="color: #000080;">:</span> Trade list<span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #000080;">...</span>
    <span style="color: #505090;">trades</span> <span style="color: #000080;">|&gt;</span> List<span style="color: #000080;">.</span><span style="color: #505090;">iter</span> <span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">fun</span> t <span style="color: #000080;">-&gt;</span>
        <span style="color: #06c; font-weight: bold;">match</span> t <span style="color: #06c; font-weight: bold;">with</span> 
        <span style="color: #000080;">|</span> SwapTrade s <span style="color: #000080;">-&gt;</span> <span style="color: #060; font-style: italic;">(* do something with s *)</span> <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span> 
        <span style="color: #000080;">|</span> SwaptionTrade st <span style="color: #000080;">-&gt;</span> <span style="color: #060; font-style: italic;">(* do something with st, which is of type Swaption *)</span> <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
        <span style="color: #000080;">&#41;</span></pre></div></div>

<p><div id="attachment_1082" class="wp-caption alignright" style="width: 310px"><a href="http://www.voyce.com/wp-content/uploads/2010/10/pattern_warning.png"><img src="http://www.voyce.com/wp-content/uploads/2010/10/pattern_warning-300x71.png" alt="Pattern matching warning" title="pattern_warning" width="300" height="71" class="size-medium wp-image-1082" /></a><p class="wp-caption-text">Pattern matching warning</p></div>And one of the big advantages here is that we get compile time checking; the compiler will warn us if we fail to deal with any of the union cases. In other words, if we add a new case to the <code>Trade</code> union, we&#8217;ll get a warning if we fail to deal with it wherever we&#8217;ve pattern-matched against it. In fact, that&#8217;s the fundamental difference between this and the interface approach; in theory the interface approach means we can chuck anything we like at it; as long as it supports the interface it will work. In the discriminated union version we&#8217;re being explicit about exactly what types we can handle.</p>
<p>Hope you found this useful. As a long-term OO developer moving to functional programming it certainly helps me to see how aspects of FP can be applied to common OO problems. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2010/11/29/fsharp-positive-discrimination/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Quick post: Using Mono.Cecil and F# to get assembly dependencies</title>
		<link>http://www.voyce.com/index.php/2010/10/31/quick-post-using-mono-cecil-and-f-to-get-assembly-dependencies/</link>
		<comments>http://www.voyce.com/index.php/2010/10/31/quick-post-using-mono-cecil-and-f-to-get-assembly-dependencies/#comments</comments>
		<pubDate>Sun, 31 Oct 2010 13:31:43 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[cecil]]></category>
		<category><![CDATA[DGML]]></category>
		<category><![CDATA[dll]]></category>
		<category><![CDATA[gac]]></category>
		<category><![CDATA[mono]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=996</guid>
		<description><![CDATA[Using Mono.Cecil and F# to list assembly dependencies.]]></description>
			<content:encoded><![CDATA[<p>One of the tools I use a lot when doing C++ development and debugging is <a href="http://www.dependencywalker.com/">&#8220;dependency walker&#8221;</a>; an app that displays all the static dependencies of an executable. These are dependencies created by referencing functions from an import library (.lib file) at compile time. If any of the imported DLLs are missing at run-time, the executable will fail to load, normally with error 2: file not found. Obviously pretty disastrous in production. The .NET equivalent is the binding failure. You can track down what went wrong at runtime using fuslogvw, but I&#8217;ve often wished for a tool like &#8216;depends&#8217; to work out up-front what dependencies are required. Luckily because assemblies includes a list of dependent libraries in the form of a manifest this information can be accessed using reflection.</p>
<p><img src="http://www.voyce.com/wp-content/uploads/2010/10/Mono-gorilla-aqua.100px.png" alt="Mono-gorilla-aqua.100px" title="Mono-gorilla-aqua.100px" width="100" height="120" class="alignleft size-full wp-image-1095" />I&#8217;m a big fan of the <a href="http://www.mono-project.com/Cecil">Mono.Cecil</a> library for doing reflection (and more!) with .NET. I&#8217;ve had issues in the past where the built-in .NET reflection (using Assembly.ReflectionOnlyLoad) attempts to load dependent libraries as you iterate over exposed types, even though it&#8217;s not supposed to (unfortunately I don&#8217;t have a repro to hand). This makes it very difficult to work on an assembly without having all of its dependencies available. Cecil doesn&#8217;t have this problem because it accesses the assembly in a lower-level way.<br />
<span id="more-996"></span><br />
I downloaded and installed <a href="http://www.go-mono.com/mono-downloads/download.html">Mono</a> (the latest version is 2.8) and referenced it from the installed Mono GAC location. Then it was just a matter of a handful of lines of F# (after a bit of spelunking through the Cecil API to find the methods relating to assembly references).</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #066; font-weight: bold;">#r @&quot;C:\Program Files (x86)\Mono-2.8\lib\mono\gac\Mono.Cecil\0.6.9.0__0738eb9f132ed756\Mono.Cecil.dll&quot;</span>
<span style="color: #066; font-weight: bold;">#r @&quot;gachelper.dll&quot;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">open</span> System
<span style="color: #06c; font-weight: bold;">open</span> System<span style="color: #000080;">.</span><span style="color: #505090;">IO</span>
<span style="color: #06c; font-weight: bold;">open</span> Mono<span style="color: #000080;">.</span><span style="color: #505090;">Cecil</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">let</span> getReferencedAssemblies <span style="color: #000080;">&#40;</span>asm <span style="color: #000080;">:</span> string<span style="color: #000080;">&#41;</span> <span style="color: #000080;">:</span> string list <span style="color: #000080;">=</span>
    <span style="color: #06c; font-weight: bold;">let</span> ad <span style="color: #000080;">=</span> AssemblyFactory<span style="color: #000080;">.</span><span style="color: #505090;">GetAssembly</span> asm
    <span style="color: #06c; font-weight: bold;">let</span> refs <span style="color: #000080;">=</span> ad<span style="color: #000080;">.</span><span style="color: #505090;">MainModule</span><span style="color: #000080;">.</span><span style="color: #505090;">AssemblyReferences</span>
    refs 
    <span style="color: #000080;">|&gt;</span> Seq<span style="color: #000080;">.</span><span style="color: #505090;">cast</span> 
    <span style="color: #000080;">|&gt;</span> Seq<span style="color: #000080;">.</span><span style="color: #505090;">fold</span> <span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">fun</span> found <span style="color: #000080;">&#40;</span>r <span style="color: #000080;">:</span> AssemblyNameReference<span style="color: #000080;">&#41;</span> <span style="color: #000080;">-&gt;</span> 
        <span style="color: #06c; font-weight: bold;">let</span> fullPath <span style="color: #000080;">=</span> ref <span style="color: #008080;">&quot;&quot;</span>
        <span style="color: #06c; font-weight: bold;">match</span> gachelper<span style="color: #000080;">.</span><span style="color: #505090;">GAC</span><span style="color: #000080;">.</span><span style="color: #505090;">TryGetFullPath</span> <span style="color: #000080;">&#40;</span>r<span style="color: #000080;">.</span><span style="color: #505090;">Name</span>, fullPath<span style="color: #000080;">&#41;</span> <span style="color: #06c; font-weight: bold;">with</span>
        <span style="color: #000080;">|</span> <span style="color: #06c; font-weight: bold;">false</span> <span style="color: #000080;">-&gt;</span> found @ <span style="color: #000080;">&#91;</span> Path<span style="color: #000080;">.</span><span style="color: #505090;">Combine</span> <span style="color: #000080;">&#91;</span><span style="color: #000080;">|</span><span style="color: #000080;">&#40;</span>System<span style="color: #000080;">.</span><span style="color: #505090;">IO</span><span style="color: #000080;">.</span><span style="color: #505090;">Path</span><span style="color: #000080;">.</span><span style="color: #505090;">GetDirectoryName</span> asm<span style="color: #000080;">&#41;</span><span style="color: #000080;">;</span> r<span style="color: #000080;">.</span><span style="color: #505090;">Name</span> <span style="color: #000080;">+</span> <span style="color: #008080;">&quot;.dll&quot;</span><span style="color: #000080;">|</span><span style="color: #000080;">&#93;</span> <span style="color: #000080;">&#93;</span>
        <span style="color: #000080;">|</span> <span style="color: #06c; font-weight: bold;">true</span> <span style="color: #000080;">-&gt;</span> found @ <span style="color: #000080;">&#91;</span><span style="color: #000080;">!</span>fullPath<span style="color: #000080;">&#93;</span>        
        <span style="color: #000080;">&#41;</span> <span style="color: #000080;">&#91;</span><span style="color: #000080;">&#93;</span></pre></div></div>

<p>As you can see I&#8217;ve also used a little C++/CLI wrapper around the GAC to get access to full paths of installed assemblies (which only works with the Microsoft CLR), but I&#8217;ll talk about that in a separate post, or you can grab the code <a href="http://github.com/voyce/gachelper">here</a>.</p>
<p>Now, we can call our function to get the set of dependencies, e.g. by using F# interactive, we also happen to be getting the dependencies *of* FSI:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #000080;">&gt;</span> getReferencedAssemblies <span style="">@&quot;C:\Program Files (x86)\FSharp-2.0.0.0\bin\fsi.exe&quot;</span><span style="color: #000080;">;;</span>
<span style="color: #06c; font-weight: bold;">val</span> it <span style="color: #000080;">:</span> string list <span style="color: #000080;">=</span>
  <span style="color: #000080;">&#91;</span><span style="color: #008080;">&quot;C:<span style="color: #008080; font-weight: bold;">\W</span>indows<span style="color: #008080; font-weight: bold;">\M</span>icrosoft.Net<span style="color: #008080; font-weight: bold;">\a</span>ssembly<span style="color: #008080; font-weight: bold;">\G</span>AC_32<span style="color: #008080; font-weight: bold;">\m</span>scorlib<span style="color: #008080; font-weight: bold;">\v</span>4.0_4.0.0.0__b77a5c561934e089<span style="color: #008080; font-weight: bold;">\m</span>scorlib.dll&quot;</span><span style="color: #000080;">;</span>
   <span style="color: #008080;">&quot;C:<span style="color: #008080; font-weight: bold;">\W</span>indows<span style="color: #008080; font-weight: bold;">\M</span>icrosoft.Net<span style="color: #008080; font-weight: bold;">\a</span>ssembly<span style="color: #008080; font-weight: bold;">\G</span>AC_MSIL<span style="color: #008080; font-weight: bold;">\F</span>Sharp.Core<span style="color: #008080; font-weight: bold;">\v</span>4.0_4.0.0.0__b03f5f7f11d50a3a<span style="color: #008080; font-weight: bold;">\F</span>Sharp.Core.dll&quot;</span><span style="color: #000080;">;</span>
   <span style="color: #008080;">&quot;C:<span style="color: #008080; font-weight: bold;">\W</span>indows<span style="color: #008080; font-weight: bold;">\M</span>icrosoft.Net<span style="color: #008080; font-weight: bold;">\a</span>ssembly<span style="color: #008080; font-weight: bold;">\G</span>AC_MSIL<span style="color: #008080; font-weight: bold;">\F</span>Sharp.Compiler<span style="color: #008080; font-weight: bold;">\v</span>4.0_4.0.0.0__b03f5f7f11d50a3a<span style="color: #008080; font-weight: bold;">\F</span>Sharp.Compiler.dll&quot;</span><span style="color: #000080;">;</span>
   <span style="color: #008080;">&quot;C:<span style="color: #008080; font-weight: bold;">\W</span>indows<span style="color: #008080; font-weight: bold;">\M</span>icrosoft.Net<span style="color: #008080; font-weight: bold;">\a</span>ssembly<span style="color: #008080; font-weight: bold;">\G</span>AC_MSIL<span style="color: #008080; font-weight: bold;">\S</span>ystem.Windows.Forms<span style="color: #008080; font-weight: bold;">\v</span>4.0_4.0.0.0__b77a5c561934e089<span style="color: #008080; font-weight: bold;">\S</span>ystem.Windows.Forms.dll&quot;</span><span style="color: #000080;">;</span>
   <span style="color: #008080;">&quot;C:<span style="color: #008080; font-weight: bold;">\W</span>indows<span style="color: #008080; font-weight: bold;">\M</span>icrosoft.Net<span style="color: #008080; font-weight: bold;">\a</span>ssembly<span style="color: #008080; font-weight: bold;">\G</span>AC_MSIL<span style="color: #008080; font-weight: bold;">\F</span>Sharp.Compiler.Interactive.Settings<span style="color: #008080; font-weight: bold;">\v</span>4.0_4.0.0.0__b03f5f7f11d50a3a<span style="color: #008080; font-weight: bold;">\F</span>Sharp.Compiler.Interactive.Settings.dll&quot;</span><span style="color: #000080;">;</span>
   <span style="color: #008080;">&quot;C:<span style="color: #008080; font-weight: bold;">\W</span>indows<span style="color: #008080; font-weight: bold;">\M</span>icrosoft.Net<span style="color: #008080; font-weight: bold;">\a</span>ssembly<span style="color: #008080; font-weight: bold;">\G</span>AC_MSIL<span style="color: #008080; font-weight: bold;">\F</span>Sharp.Compiler.Server.Shared<span style="color: #008080; font-weight: bold;">\v</span>4.0_4.0.0.0__b03f5f7f11d50a3a<span style="color: #008080; font-weight: bold;">\F</span>Sharp.Compiler.Server.Shared.dll&quot;</span><span style="color: #000080;">;</span>
   <span style="color: #008080;">&quot;C:<span style="color: #008080; font-weight: bold;">\W</span>indows<span style="color: #008080; font-weight: bold;">\M</span>icrosoft.Net<span style="color: #008080; font-weight: bold;">\a</span>ssembly<span style="color: #008080; font-weight: bold;">\G</span>AC_MSIL<span style="color: #008080; font-weight: bold;">\S</span>ystem<span style="color: #008080; font-weight: bold;">\v</span>4.0_4.0.0.0__b77a5c561934e089<span style="color: #008080; font-weight: bold;">\S</span>ystem.dll&quot;</span><span style="color: #000080;">&#93;</span></pre></div></div>

<p>This is, of course, the tip of the iceberg in terms of Cecil functionality; there are lots of far more interesting things you can do &#8211; like IL extraction and re-writing &#8211; things which are impossible to do with the Microsoft reflection API.</p>
<p>I ended up using this code to generate DGML graphs that can be opened and explored using VS2010. This functionality comes &#8220;in the box&#8221; with VS2010 Architecture Explorer in the Ultimate Edition &#8211; but who can afford that&#8230;? We can do much the same ourselves by just using the information we get from Cecil and spitting out DGML directly. The files can be opened read-only in the Premium edition for perusal.</p>
<p>For the curious, here&#8217;s the (somewhat fugly and imperative) F# code to generate the DGML file. It creates a minimal file that only contains <code>Link</code> elements; Visual Studio will &#8220;fill in the blanks&#8221; by adding the nodes themselves when you open the file.</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">let</span> genDgml asm <span style="color: #000080;">&#40;</span>out <span style="color: #000080;">:</span> string<span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
    <span style="color: #06c; font-weight: bold;">let</span> doc <span style="color: #000080;">=</span> XmlDocument<span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
    <span style="color: #06c; font-weight: bold;">let</span> nsURI <span style="color: #000080;">=</span> <span style="color: #008080;">&quot;http://schemas.microsoft.com/vs/2009/dgml&quot;</span>
    <span style="color: #06c; font-weight: bold;">let</span> nsmgr <span style="color: #000080;">=</span> XmlNamespaceManager<span style="color: #000080;">&#40;</span>doc<span style="color: #000080;">.</span><span style="color: #505090;">NameTable</span><span style="color: #000080;">&#41;</span>
    nsmgr<span style="color: #000080;">.</span><span style="color: #505090;">AddNamespace</span><span style="color: #000080;">&#40;</span><span style="color: #008080;">&quot;&quot;</span>, nsURI<span style="color: #000080;">&#41;</span>
    <span style="color: #06c; font-weight: bold;">let</span> root <span style="color: #000080;">=</span> doc<span style="color: #000080;">.</span><span style="color: #505090;">CreateElement</span><span style="color: #000080;">&#40;</span><span style="color: #008080;">&quot;DirectedGraph&quot;</span>, nsURI<span style="color: #000080;">&#41;</span>
    <span style="color: #06c; font-weight: bold;">let</span> links <span style="color: #000080;">=</span> doc<span style="color: #000080;">.</span><span style="color: #505090;">CreateElement</span><span style="color: #000080;">&#40;</span><span style="color: #008080;">&quot;Links&quot;</span>, nsURI<span style="color: #000080;">&#41;</span>
    <span style="color: #06c; font-weight: bold;">let</span> <span style="color: #06c; font-weight: bold;">rec</span> genRefs added asm <span style="color: #000080;">=</span>
        getReferencedAssemblies asm
        <span style="color: #000080;">|&gt;</span> List<span style="color: #000080;">.</span><span style="color: #505090;">fold</span> <span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">fun</span> added dep <span style="color: #000080;">-&gt;</span> 
            <span style="color: #06c; font-weight: bold;">let</span> link <span style="color: #000080;">=</span> doc<span style="color: #000080;">.</span><span style="color: #505090;">CreateElement</span><span style="color: #000080;">&#40;</span><span style="color: #008080;">&quot;Link&quot;</span>, nsURI<span style="color: #000080;">&#41;</span>
            link<span style="color: #000080;">.</span><span style="color: #505090;">SetAttribute</span><span style="color: #000080;">&#40;</span><span style="color: #008080;">&quot;Source&quot;</span>, Path<span style="color: #000080;">.</span><span style="color: #505090;">GetFileNameWithoutExtension</span> asm<span style="color: #000080;">&#41;</span>
            link<span style="color: #000080;">.</span><span style="color: #505090;">SetAttribute</span><span style="color: #000080;">&#40;</span><span style="color: #008080;">&quot;Target&quot;</span>, Path<span style="color: #000080;">.</span><span style="color: #505090;">GetFileNameWithoutExtension</span> dep<span style="color: #000080;">&#41;</span>
            ignore <span style="color: #000080;">&lt;|</span> links<span style="color: #000080;">.</span><span style="color: #505090;">AppendChild</span> link
            <span style="color: #06c; font-weight: bold;">if</span> not <span style="color: #000080;">&lt;|</span> <span style="color: #000080;">&#40;</span>added <span style="color: #000080;">|&gt;</span> Map<span style="color: #000080;">.</span><span style="color: #505090;">containsKey</span> dep<span style="color: #000080;">&#41;</span>
            <span style="color: #06c; font-weight: bold;">then</span> genRefs <span style="color: #000080;">&#40;</span>added<span style="color: #000080;">.</span><span style="color: #505090;">Add</span> <span style="color: #000080;">&#40;</span>dep, <span style="color: #06c; font-weight: bold;">false</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span> dep
            <span style="color: #06c; font-weight: bold;">else</span> added
        <span style="color: #000080;">&#41;</span> added
    ignore <span style="color: #000080;">&lt;|</span> genRefs Map<span style="color: #000080;">.</span><span style="color: #505090;">empty</span> asm
    ignore <span style="color: #000080;">&lt;|</span> root<span style="color: #000080;">.</span><span style="color: #505090;">AppendChild</span> links
    ignore <span style="color: #000080;">&lt;|</span> doc<span style="color: #000080;">.</span><span style="color: #505090;">AppendChild</span> root
    doc<span style="color: #000080;">.</span><span style="color: #505090;">Save</span> out</pre></div></div>

<p><div id="attachment_1101" class="wp-caption alignright" style="width: 310px"><a href="http://www.voyce.com/wp-content/uploads/2010/10/dgml.png"><img src="http://www.voyce.com/wp-content/uploads/2010/10/dgml-300x158.png" alt="The DGML in cluster view" title="dgml" width="300" height="158" class="size-medium wp-image-1101" /></a><p class="wp-caption-text">The DGML in cluster view</p></div>If you run it against the FSI.exe as we did before it will chug away for a while and then generate this file, which contains all of the dependencies.</p>
<p>It can be quite enlightening, as well as useful, to see your app dependencies laid-bare before you&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2010/10/31/quick-post-using-mono-cecil-and-f-to-get-assembly-dependencies/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Public static fields gone from F# 2.0</title>
		<link>http://www.voyce.com/index.php/2010/10/01/public-static-fields-gone-from-f-2-0/</link>
		<comments>http://www.voyce.com/index.php/2010/10/01/public-static-fields-gone-from-f-2-0/#comments</comments>
		<pubDate>Fri, 01 Oct 2010 17:00:53 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[DependencyProperty]]></category>
		<category><![CDATA[IL]]></category>
		<category><![CDATA[wpf]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=900</guid>
		<description><![CDATA[You can no longer create public static fields in F# 2.0. Why was the change made and what impact does it have on WPF development?]]></description>
			<content:encoded><![CDATA[<p>There have been quite a few changes in F# version 2.0, which shipped as the first &#8220;official&#8221; version of the language as part of Visual Studio 2010. Most of the changes are detailed in various release notes on Don Syme&#8217;s blog and other places, but unfortunately one of the more significant changes passed me by, and turned out to be quite significant in the context of WPF development: public static fields are no longer supported. But what does this mean? </p>
<h3>The change</h3>
<p>The change itself is simple: static fields can no longer be public. Static fields can still be created, but they must be private. </p>
<p>In pre-2.0 versions of F# it was possible to declare a static field on a type like this:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">type</span> MyType<span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
    <span style="color: #000080;">&#91;</span><span style="color: #000080;">&lt;</span>DefaultValue<span style="color: #000080;">&gt;</span><span style="color: #000080;">&#93;</span>
    <span style="color: #06c; font-weight: bold;">static</span> <span style="color: #06c; font-weight: bold;">val</span> <span style="color: #06c; font-weight: bold;">mutable</span> <span style="color: #06c; font-weight: bold;">public</span> MyProperty <span style="color: #000080;">:</span> int</pre></div></div>

<p>Resulting in a type containing a static field, as you&#8217;d expect:</p>
<pre>
    .field public static int32 MyProperty
</pre>
<p>The code now generates the compiler error:</p>
<p><code>error FS0881: Static 'val' fields in types must be mutable, private and marked with the '[&lt;DefaultValue&gt;]' attribute. They are initialized to the 'null' or 'zero' value for their type. Consider also using a 'static let mutable' binding in a class type.</code></p>
<p>Notice that there are already some gnarly aspects to the definition of the property; notably the use of the <code>[&lt;DefaultValue&gt;]</code> attribute, which indicates that the field is un-initialized. This gives us a hint that there might be some inherent problems.</p>
<h3>Why do we even need them?</h3>
<p>In a word or three: WPF dependency properties. </p>
<p>The recommended way of implementing dependency properties in other .NET languages is to use public static fields, e.g. in C#:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">readonly</span> DependencyProperty MyPropertyProperty <span style="color: #008000;">=</span>
        DependencyProperty.<span style="color: #0000FF;">Register</span><span style="color: #000000;">&#40;</span> 
          <span style="color: #666666;">&quot;MyProperty&quot;</span>, <span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span><span style="color: #000000;">&#41;</span>, <span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>MyType<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>This is one of the few places where C# is terser than F#. Here we can declare and define the value in one line (ish), whereas F# requires a separate declaration of the field (as above) then initialisation in the static constructor (<code>static do</code>).</p>
<h3>Why was it removed?</h3>
<p>I got the answer from the horse&#8217;s mouth. Don Syme said that:</p>
<blockquote><p>
We deliberately removed the ability to create public static fields in Beta2/RC, because of issues associated with initialization of the fields (i.e. ensuring the “static do” bindings are run correctly, and if they are run, then they are run for the whole file, in the right order, with no deadlocks or uninitialized access when initialization occurs from multiple threads).</p></blockquote>
<p>You can imagine how this would be a problem; there would need to be a way of ensuring that whichever static field was accessed it caused the static constructor to run, which may itself access static fields. All pretty nasty. In fact, Don mentioned that C# suffers from much the same synchronisation issues, but just tends to be used in a way that means it&#8217;s less likely to be noticed!</p>
<h3>The alternative</h3>
<p>At least in theory it&#8217;s possible to create a type that uses static properties rather than static fields to store its registered DependencyProperty information.</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">type</span> Foo <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
    <span style="color: #06c; font-weight: bold;">inherit</span> FrameworkElement<span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
    <span style="color: #06c; font-weight: bold;">static</span> <span style="color: #06c; font-weight: bold;">mutable</span> <span style="color: #06c; font-weight: bold;">private</span> _myPropertyInternal <span style="color: #000080;">:</span> DependencyProperty 
    <span style="color: #06c; font-weight: bold;">static</span> <span style="color: #06c; font-weight: bold;">member</span> this<span style="color: #000080;">.</span><span style="color: #505090;">MyProperty</span> <span style="color: #06c; font-weight: bold;">with</span> get <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span> _myPropertyInternal</pre></div></div>

<p>Whether or not this works depends very much on how calling code accesses DependencyProperty information. If it uses reflection to access the field directly it will obviously fail. But if it uses a more robust/flexible method then it should be OK. Empirically it seems that the WPF framework code itself does the latter, for instance, when it&#8217;s instantiating objects from XAML, and it works properly independently of how it&#8217;s implemented. </p>
<h3>The conclusion</h3>
<p>So the conclusion is &#8220;wontfix&#8221;: the behaviour is by design. Unfortunately it has the effect that it&#8217;s no longer possible to create a type with an identical IL &#8220;signature&#8221; in both F# and C#. It seems a bit of a shame, but I guess the trade-off is that we&#8217;re protected against insiduous initialisation issues, so it will probably turn out to be the right thing in the long term.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2010/10/01/public-static-fields-gone-from-f-2-0/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Minilight renderer in F#</title>
		<link>http://www.voyce.com/index.php/2010/06/30/minilight-renderer-in-fsharp/</link>
		<comments>http://www.voyce.com/index.php/2010/06/30/minilight-renderer-in-fsharp/#comments</comments>
		<pubDate>Wed, 30 Jun 2010 17:19:43 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[monte carlo]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=938</guid>
		<description><![CDATA[Porting the Minilight global illumination renderer to F#.]]></description>
			<content:encoded><![CDATA[<p><div id="attachment_961" class="wp-caption alignleft" style="width: 150px"><a href="http://www.voyce.com/wp-content/uploads/2010/06/cornellbox-e.png"><img src="http://www.voyce.com/wp-content/uploads/2010/06/cornellbox-e.png" alt="Cornell Box in the evening" title="cornellbox-e" width="140" height="140" class="size-full wp-image-961" /></a><p class="wp-caption-text">Cornell Box in the evening</p></div>I&#8217;m a sucker for eye-candy, and the other day I came across the beautifully lit renders produced by <a href="http://www.hxa.name/minilight/">Minilight</a>. It&#8217;s a nice, minimal implementation of a global illumination renderer that&#8217;s been ported to a wide variety of different languages from C to ActionScript. So of course, I couldn&#8217;t resist trying to implement it in F#.<br />
<span id="more-938"></span></p>
<h3>What is a &#8220;global illumination renderer&#8221;?</h3>
<p>In short; a global illumination renderer attempts to simulate the way that light behaves in the real world. It bounces rays of light around the scene, noting which surfaces are hit, and how each of them affects the ray. Of course real light travels fast &#8211; at about the speed of light, in fact &#8211; and our simulated rays can&#8217;t match that, so although the resulting effect looks natural, it&#8217;s not a very efficient way of getting there. Graphics systems that need to be near real-time (i.e. games), use a variety of short-cuts to try and get the same effect without requiring the same amount of number crunching.</p>
<p>Even this implementation is forced to use a couple of techniques to improve performance, I won&#8217;t go into them here, as they&#8217;re explained pretty thoroughly on the Minilight site. </p>
<p>Interestingly the algorithm uses a Monte Carlo technique to simulate the random path of the ray through the scene and the same technique is used in finance to model how the price of an asset will change through time. </p>
<h3>Translating to F#</h3>
<p><div id="attachment_970" class="wp-caption alignright" style="width: 160px"><a href="http://www.voyce.com/wp-content/uploads/2010/06/roomfront.sun.ml.png"><img src="http://www.voyce.com/wp-content/uploads/2010/06/roomfront.sun.ml-150x150.png" alt="Room with sun and light, 800 paths per pixel" title="roomfront.sun.ml" width="150" height="150" class="size-thumbnail wp-image-970" /></a><p class="wp-caption-text">Room with sun and light, 800 paths per pixel</p></div>Luckily, the existing OCaml version is considered one of the reference implementations, and as ML is the spiritual predecessor of F# I didn&#8217;t expect it to be too difficult to port. It wasn&#8217;t. I&#8217;m no ML expert, so some of the language features were a bit of a surprise; things like the use of a dot on all of the operators, but these are pretty minimal syntactic differences.</p>
<p>Some of the ML constructs caused warnings from the F# compiler as I didn&#8217;t use the explicit ML compatibility mode. For instance, the use of the <code>^</code> operator to concatenate strings:<br />
<code><br />
warning FS0062: This construct is for ML compatibility. Consider using the '+' operator instead. This may require a type annotation to indicate it acts on strings.<br />
</code><br />
Some other changes included:</p>
<ul>
<li>Using dot rather than # notation to access class members</li>
<li>Using square bracket for array element access (<code>array.[n]</code> rather than <code>array.(n)</code>)</li>
<li>Removing <code>let...and</code> for non-recursive bindings</li>
</ul>
<p>There was also the opportunity to make use of some of the .NET framework classes, things like <code>System.Drawing.Bitmap</code> to write pixels directly into a bitmap and then save it into a .PNG file. Much easier than trying to find something to read the .PPM file that the original version emits.    </p>
<h3>Potential improvements</h3>
<p>One of the most obvious improvements that could be made is to make use of the parallelism support in F# and .NET. The algorithm itself is easily (if not embarrassingly) parallelisable, given that it iterates over the pixels in the output image, and performs independent operations on each of them. Unfortunately I haven&#8217;t had a chance to look at this yet &#8211; and the Windows VM I&#8217;m using only has a single processor anyway, so on a purely selfish note, I wouldn&#8217;t see any immediate performance improvements.  It should be as simple as changing the pixel loop to use <code>Parallel.For</code>, or creating an <code>async</code> computation expression.</p>
<p>Something else to note: I err&#8217;d on the side of caution when it comes to saving intermediate images, so every iteration it creates and writes the file. This will be doing lots of allocation and strictly unnecessary work, especially for simple scenes.</p>
<p>Given this approach is so completely compute bound it would be interesting to see how moving some of the calculations to a GPU would affect it. It might even be possible to use quotations for some of the inner loops and then generate Nvidia intermediate language (PTX) from them &#8211; that&#8217;s something I&#8217;ve been wanting to do for a while. </p>
<p>I did run the code through the Visual Studio 2010 profiler to get a rough idea of where the time was being spent; it looked like the majority was in the leaf of the calculations where numerical operations where being performed on the vectors, which is consistent with what we&#8217;d expect.</p>
<h3>Use the source</h3>
<p>So, here&#8217;s the source. No warranties implied, use at your own risk, your mileage may vary, all errors are mine etc, etc.<br />
<a href='http://www.voyce.com/wp-content/uploads/2010/06/minilight_fsharp.zip'>minilight_fsharp</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2010/06/30/minilight-renderer-in-fsharp/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Calling MSBuild tasks with F#</title>
		<link>http://www.voyce.com/index.php/2010/03/31/calling-msbuild-tasks-with-fsharp/</link>
		<comments>http://www.voyce.com/index.php/2010/03/31/calling-msbuild-tasks-with-fsharp/#comments</comments>
		<pubDate>Wed, 31 Mar 2010 17:31:15 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[msbuild]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=774</guid>
		<description><![CDATA[It's easy to call MSBuild tasks directly from F#. Although possibly unnecessary.]]></description>
			<content:encoded><![CDATA[<p>The other day I was trying to understand some strange behaviour in msbuild with regard to how it resolves referenced assemblies. I thought I&#8217;d try directly invoking the tasks that are used during the build, specifically <a href="http://msdn.microsoft.com/en-us/library/9ad3f294.aspx">ResolveAssemblyReference</a>, so that I could experiment with them in F# interactive. It turned out to be pretty straightforward.<br />
<span id="more-774"></span><br />
In this example I&#8217;m attempting to resolve a reference to &#8220;class1.dll&#8221; from the GAC, taking into account the contents of the app.config (which can be used change the version resolution in MSBuild):</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #066; font-weight: bold;">#I @&quot;C:\winnt\Microsoft.NET\Framework\v2.0.50727\&quot;</span>
<span style="color: #066; font-weight: bold;">#r @&quot;Microsoft.Build.Tasks.dll&quot;</span>
<span style="color: #066; font-weight: bold;">#r @&quot;Microsoft.Build.Utilities.dll&quot;</span>
<span style="color: #066; font-weight: bold;">#r @&quot;Microsoft.Build.Framework.dll&quot;</span>
<span style="color: #066; font-weight: bold;">#r @&quot;Microsoft.Build.Engine.dll&quot;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">open</span> System
<span style="color: #06c; font-weight: bold;">open</span> Microsoft<span style="color: #000080;">.</span><span style="color: #505090;">Build</span><span style="color: #000080;">.</span><span style="color: #505090;">Framework</span>
<span style="color: #06c; font-weight: bold;">open</span> Microsoft<span style="color: #000080;">.</span><span style="color: #505090;">Build</span><span style="color: #000080;">.</span><span style="color: #505090;">Utilities</span>
<span style="color: #06c; font-weight: bold;">open</span> Microsoft<span style="color: #000080;">.</span><span style="color: #505090;">Build</span><span style="color: #000080;">.</span><span style="color: #505090;">Tasks</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">do</span>
    <span style="color: #06c; font-weight: bold;">let</span> t <span style="color: #000080;">=</span> 
        ResolveAssemblyReference<span style="color: #000080;">&#40;</span>Silent <span style="color: #000080;">=</span> <span style="color: #06c; font-weight: bold;">true</span>,
            Assemblies <span style="color: #000080;">=</span> <span style="color: #000080;">&#91;</span><span style="color: #000080;">|</span> <span style="color: #06c; font-weight: bold;">upcast</span> TaskItem<span style="color: #000080;">&#40;</span> ItemSpec<span style="color: #000080;">=</span><span style="color: #008080;">&quot;class1&quot;</span> <span style="color: #000080;">&#41;</span> <span style="color: #000080;">|</span><span style="color: #000080;">&#93;</span>,
            AllowedAssemblyExtensions <span style="color: #000080;">=</span> <span style="color: #000080;">&#91;</span><span style="color: #000080;">|</span><span style="color: #008080;">&quot;.dll&quot;</span><span style="color: #000080;">|</span><span style="color: #000080;">&#93;</span>,
            AppConfigFile <span style="color: #000080;">=</span> <span style="color: #008080;">&quot;c:<span style="color: #008080; font-weight: bold;">\\</span>dev<span style="color: #008080; font-weight: bold;">\\</span>myapp<span style="color: #008080; font-weight: bold;">\\</span>myapp.exe.config&quot;</span>,
            SearchPaths <span style="color: #000080;">=</span> <span style="color: #000080;">&#91;</span><span style="color: #000080;">|</span><span style="color: #008080;">&quot;{GAC}&quot;</span><span style="color: #000080;">|</span><span style="color: #000080;">&#93;</span>
            <span style="color: #000080;">&#41;</span>
    <span style="color: #06c; font-weight: bold;">match</span> t<span style="color: #000080;">.</span><span style="color: #505090;">Execute</span><span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span> <span style="color: #06c; font-weight: bold;">with</span>
    <span style="color: #000080;">|</span> <span style="color: #06c; font-weight: bold;">true</span>  <span style="color: #000080;">-&gt;</span> printf <span style="color: #008080;">&quot;%A<span style="color: #008080; font-weight: bold;">\n</span>&quot;</span> t<span style="color: #000080;">.</span><span style="color: #505090;">ResolvedFiles</span>
    <span style="color: #000080;">|</span> <span style="color: #06c; font-weight: bold;">false</span> <span style="color: #000080;">-&gt;</span> printf <span style="color: #008080;">&quot;Task failed&quot;</span></pre></div></div>

<p>The output is:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #000080;">&#91;</span><span style="color: #000080;">|</span>C<span style="color: #000080;">:</span>\WINNT\assembly\GAC_MSIL\class1\1<span style="color: #000080;">.</span>1<span style="color: #000080;">.</span>8<span style="color: #000080;">.</span>0__120bce90f68b861a\class1<span style="color: #000080;">.</span><span style="color: #505090;">dll</span><span style="color: #000080;">|</span><span style="color: #000080;">&#93;</span></pre></div></div>

<p>The code makes good use of F#&#8217;s named constructor arguments, which map to property setters on the object we&#8217;ve just created. We can also create the arrays of <a href="http://msdn.microsoft.com/en-us/library/microsoft.build.utilities.taskitem.aspx">TaskItem</a>s and strings fairly easily, although an explicit upcast is required in order to obtain the ITaskItem (F# doesn&#8217;t upcast implicitly like many object oriented languages).</p>
<p>I&#8217;ve just discovered that Jomo Fisher wrote about <a href="http://blogs.msdn.com/jomo_fisher/archive/2008/05/22/programmatically-resolve-assembly-name-to-full-path-the-same-way-msbuild-does.aspx">exactly the same thing</a> back in May 2008! He mentions using an object expression in order to provide an implementation of <code>IBuildEngine</code>, which I&#8217;m getting away with by setting the <code>Silent</code> property on the <code>ResolveAssemblyReference</code> task, meaning that it never attempts to obtain the logging context from the build engine.</p>
<p>Another gotcha here is the fact that versions of various interfaces including <code>IBuildEngine</code> and <code>ITaskItem</code> exist in both the 2.0.0.0 and 3.5.0.0 versions of the <code>Microsoft.Build.Framework</code> assembly. Be careful that you reference the correct version for the task that you&#8217;re calling. Normally it will be the 2.0 versions, in which case you&#8217;ll need to use explicit file references in your script, adding the directory to the library include path:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #066; font-weight: bold;">#I @&quot;C:\winnt\Microsoft.NET\Framework\v2.0.50727\&quot;</span>
<span style="color: #066; font-weight: bold;">#r @&quot;Microsoft.Build.Framework.dll&quot;</span></pre></div></div>

<p>Rather than partially qualified assembly references:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #066; font-weight: bold;">#r @&quot;Microsoft.Build.Framework&quot;</span></pre></div></div>

<p>As the latter will resolve to the latest installed version of the assembly, 3.5, which is not what you want. Look out for errors like:</p>
<blockquote><p>
System.InvalidCastException: Unable to cast object of type &#8216;Microsoft.Build.Utilities.TaskItem&#8217; to type &#8216;Microsoft.Build.Framework.ITaskItem&#8217;.
</p></blockquote>
<h2>Alternatives</h2>
<p><div id="attachment_777" class="wp-caption alignleft" style="width: 310px"><a href="http://www.voyce.com/wp-content/uploads/2010/03/msbuild_verbosity.png"><img src="http://www.voyce.com/wp-content/uploads/2010/03/msbuild_verbosity-300x174.png" alt="The Tools|Options MSBuild verbosity setting" title="msbuild_verbosity" width="300" height="174" class="size-medium wp-image-777" /></a><p class="wp-caption-text">The Tools|Options MSBuild verbosity setting</p></div>Although this was a useful experiment, I discovered that it&#8217;s often much easier to just increase the MSBuild verbosity and wade through the reams of output to find what you&#8217;re after (but then <a href="http://en.wiktionary.org/wiki/yak_shaving">the Yak will remain hairy</a>). There&#8217;s an option in Tools|Options|Projects and Solutions|Build and Run to change the output level from Silent to Diagnostic. Beware: you can easily get megabytes of text output from diagnostic mode!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2010/03/31/calling-msbuild-tasks-with-fsharp/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

