<?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; .NET</title>
	<atom:link href="http://www.voyce.com/index.php/tag/net/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>C++: The oldest new kid on the block</title>
		<link>http://www.voyce.com/index.php/2011/09/18/cpp-the-oldest-new-kid-on-the-block/</link>
		<comments>http://www.voyce.com/index.php/2011/09/18/cpp-the-oldest-new-kid-on-the-block/#comments</comments>
		<pubDate>Sat, 17 Sep 2011 23:06:09 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Rant]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[win32]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=1294</guid>
		<description><![CDATA[Is C++ coming back to a warm welcome from Microsoft?  ]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.voyce.com/wp-content/uploads/2011/09/ballmer_cpp.png"><img src="http://www.voyce.com/wp-content/uploads/2011/09/ballmer_cpp.png" alt="Tasty" title="Tasty" width="200" height="200" class="alignright size-full wp-image-1296" /></a>Nobody could have failed to notice the recent resurgence of interest in the C++ programming language. In particular, the recent <a href="http://www.buildwindows.com/">Build</a> conference was the most we’ve seen Microsoft talking about C++ for several years. Why has a language that’s been languishing in the “prehistoric irrelevance” category for so long suddenly come back into vogue?<br />
<span id="more-1294"></span></p>
<h3>Dark Days</h3>
<p>We should bear in mind that in some camps, C++ never went away. The financial, scientific and games programming communities have bravely kept the fires burning.</p>
<p>Why? Primarily performance. In these industries performance is a feature, it’s a key differentiator, and it will help you make money. Can you say the same for an enterprise app (there I go, using that term disparagingly again) that just displays a form interface over a relational database?</p>
<p>However, even in the C++ bastions, the language was getting a bad press. I can only speak for the finance industry, where I’ve been working for the past 10 years, but even here the focus briefly switched away from raw performance to complex (overly-complex, dangerously-complex, as hindsight tells us) trades where getting to market first with something new was key: developer productivity was key. Flexibility and generality was key.</p>
<p>In that case, you don’t want to be dealing with the vagaries of subtle errors, crashes and memory leaks that can easily creep in when you’re using a language as low-level as C++. You just want to be able to release quickly. You probably want to be using a managed language.</p>
<p>In fact, C++ was getting a bad press all over. The functional power that was provided in languages like Haskell and F# &#8211; and being hastily added to C# &#8211; was missing or awkwardly implemented in C++. The provision of things like the .NET thread pool provided programmers on the CLR an easy way to schedule asynchronous tasks, and it was being touted as the only way to survive in the highly-parallel near-future. Of course, it was possible to do this stuff in C++, it was just more difficult.   </p>
<p>Despite this, the programming community widely understood the power that C++ brings, but also that it has to be wielded carefully. Witness the oft-repeated jokes about the fact that when you shoot yourself in the foot with C++, you tend to blow your leg off. There were even tensions within Microsoft, with the pro-managed DevDiv vs the hardcore, native-favouring Windows division.</p>
<h3>The New Order</h3>
<p>So what’s changed? Herb Sutter’s recent <a href="http://channel9.msdn.com/posts/C-and-Beyond-2011-Herb-Sutter-Why-C">talk</a> covered many of the reasons why C++ is relevant again, and the most obvious reason is the emergence and importance of mobile devices and data centres. </p>
<p>They have a completely different set of requirements than the desktop: they focus on squeezing the best experience out of every available cycle (and corresponding minute of battery life), and the most performance out of every watt of data centre power per degree of cooling. We’re seeing the impact of the smartphone in your pocket and the data-centric web and social media reflecting back onto the languages we use to write software.  </p>
<p>Managed languages fall down in some important areas here. They sacrifice memory efficiency to the god of garbage collection and they offer fewer opportunities for aggressive compiler optimisations, including, in the case of .NET, making use of chip-provided performance features like SIMD instructions.</p>
<p>Nowadays in more and more of the computing industry, it’s the hardware that’s driving the development choices, not the other way around.</p>
<p>With resource-constricted platforms, you want to be doing more of the heavy lifting offline, at compile time, not at run-time with a JIT compiler.</p>
<h3>How the iPhone showed devs don&#8217;t care</h3>
<p>While (parts of) Microsoft were busy pushing the managed languages hard, Apple was quietly producing game-changing pieces of hardware that the device-carrying public were buying in their hordes. And they weren’t just buying devices, they were buying apps to play on these devices &#8211; in their millions. Lots of developers wanted a piece of this action but &#8211; quelle horreur! &#8211; You had to use an obscure variant of C to create them.</p>
<p>But &#8211; surprise, surprise &#8211; developers did it anyway. Luckily, they weren’t on their own, but this time rather than a managed runtime, they had an API to use. And they had to use it; it was, and is, literally a condition of sale that your app uses only the APIs that Apple provide and in the way that they intended. Whatever your view on the fairness of this approach, having a restricted surface area and well defined set of libraries helps developers win back some of the productivity they might otherwise have sacrificed by using Objective-C.</p>
<p>Microsoft must’ve been looking askance at this, wondering how Apple had so effectively switched the model around. MS had been based on the idea of developer productivity being king and the hardware being utterly insignificant. Now developers were writing code in a language that was broadly derided by people in the programming community, yet they were in a virtuous circle where writing apps helped to ship hardware that increased the market for their apps. </p>
<h3>We need libraries</h3>
<p>Is it possible to find a good balance between the raw power of C++ and the productivity of managed languages? I think it is; and partly it comes down to having a good set of libraries. When I say good, I mean consistent, relevant, well-documented, easily available set of libraries. Can you see where C++ may have struggled here before?</p>
<p>For the low-level, programming task oriented basics, Boost is the answer. Seriously, Boost always seems to be the answer to questions of “how do I do X in C++?” where X is a modern programming technique. Smart pointers, lambdas, higher-order functions… they’re all there. </p>
<p>A few years ago if you were working in C++, you didn’t have many options apart from vanilla STL, Boost, and writing-it-yourself (again). Now, the STL and the language itself is richer and anecdotally, organisations are more receptive to the use of Boost. So hopefully, this combination gives us back access to most of the functionality that’s available to managed developers in their pre-packaged base class libraries.</p>
<h3>C++ and Apps</h3>
<p>But how is that going to help people use it to produce compelling apps and “experiences” (cough) and specifically, how is Microsoft going to use its developer productivity nous to keep Windows relevant in the new hardware markets? </p>
<p>They need something else; something like the Apple Core frameworks. It looks like this is what Microsoft is talking about with Windows 8 and the Windows Runtime. It’s suddenly not embarrassed to admit that, hey, Windows itself is written in C++, so maybe you shouldn’t have to go through a managed ‘interpretation’ of the existing APIs, one that’s exclusively available to managed languages.</p>
<p>Of course, Microsoft can’t do anything as radical as forcing all developers targeting a mobile or tablet platform to use C++. For them, programmers, rather than any particular hardware, are the bread-and-butter, so they tend to have a slightly less dictator-style relationship with devs than Apple does. </p>
<p>Judging from what I’ve seen from Build, Microsofts chosen approach is to provide language-specific “projections” (their term) from the Windows Runtime layer into a variety of languages, including C++. The native C++ types are mapped into corresponding concepts in the vernacular of the higher level languages; Javascript, C# etc. They’ve gone to some lengths, it seems, to ensure that transitions between levels are efficient. Using C++ at both levels should be the fast path, and of course you can mix it freely with code that, for example, uses Boost or other C++ libraries. </p>
<p>Additionally and importantly, as well as basic types, collections etc, the Windows Runtime also contains all of the rich APIs for accessing app-level functionality; things like image capture, sound and geolocation. So suddenly, all of this stuff is available in all its glory directly from C++ &#8211; and other languages too via cheap bridges. What they’ve essentially got is an identical copy of the architecture that exists in the iOS world, while still attempting to keep non C++ developers on-side. </p>
<h3>The Return&#8230;?</h3>
<p>So, have Microsoft managed to bring C++ in from the cold? They seem to have admitted, at least to themselves, that developers will need to use it in order to effectively target some platforms, and they’ve used their tooling experience to make it look and feel like a managed language in their IDEs, as well as leveraging their compiler technology to do some additional useful performance tricks. It feels like C++ was a fundamental concern in the redesign of the new alternative to the creaking Win32 API.</p>
<p>But will the transition be something to make current developers switch to C++, especially those who’ve been used to living in the cosseted managed world? Perhaps, if the Microsoft-based tablet market becomes as compelling &#8211; read, large &#8211; as Apple’s. Otherwise I don’t see any reason why developers who don’t have specific platform or other runtime requirements would move; for the majority of environments, developer time is still the dominant cost, so developer productivity will still be paramount. </p>
<p>The gap between managed and unmanaged languages has certainly narrowed in that area, but it still exists. C++ is still proving surprisingly relevant, despite its 30+ years, and hopefully its use in new and different areas of computing will feed back into improvements in the language and libraries for everyone’s benefit. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2011/09/18/cpp-the-oldest-new-kid-on-the-block/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>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>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>.NET 4.0 Type Equivalence causes BadImageFormatException</title>
		<link>http://www.voyce.com/index.php/2010/04/23/net-4-0-type-equivalence-causes-badimageformatexception/</link>
		<comments>http://www.voyce.com/index.php/2010/04/23/net-4-0-type-equivalence-causes-badimageformatexception/#comments</comments>
		<pubDate>Fri, 23 Apr 2010 10:53:33 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[COM]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[WinDbg]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[.NET4]]></category>
		<category><![CDATA[CLR]]></category>
		<category><![CDATA[IL]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=840</guid>
		<description><![CDATA[Interop assemblies containing certain constructs will cause a BadImageFormatException in .NET 4.0]]></description>
			<content:encoded><![CDATA[<p>I recently discovered a nasty backward compatibility problem with the new type equivalence feature in .NET 4.0. Luckily it&#8217;s relatively difficult to hit it if you&#8217;re in a pure-C# environment, but if you happen to generate any assemblies directly using IL, you should watch out. Read on for all the gory details.<br />
<span id="more-840"></span></p>
<h2>What is .NET type equivalence?</h2>
<p>Described at a high level <a href="http://msdn.microsoft.com/en-us/library/dd997297.aspx">here</a>, .NET 4.0 type equivalence essentially gives you a way of indicating that different .NET types represent the same underlying COM type and is most commonly used in COM interop scenarios. One of the reasons for its introduction is to save developers from having to ship large interop DLLs with their software, e.g. the multi-megabyte Microsoft.Office.Interop. Instead the compiler can inline the definition of any types used, and mark them appropriately as representing the original COM types. </p>
<h2>The error</h2>
<p>We noticed that whenever we built and ran an application that referenced a DLL using .NET 2.0, it worked. Doing the same thing with .NET 4.0 caused a <a href="http://msdn.microsoft.com/en-us/library/system.badimageformatexception.aspx">BadImageFormatException</a>.<br />
<code><br />
Unhandled Exception: System.BadImageFormatException: Could not load file or assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. An attempt was made to load a program with an incorrect format.<br />
   at X.Main()<br />
</code> </p>
<h2>Let&#8217;s dig!</h2>
<p>So, the BadImageFormatException doesn&#8217;t actually tell us much. Let&#8217;s break out WinDbg and see what we can find. Running the faulting app we can see several C++ exceptions before the CLR exception is thrown:<br />
<code><br />
(178c.790): C++ EH exception - code e06d7363 (first chance)<br />
...<br />
(178c.790): C++ EH exception - code e06d7363 (first chance)<br />
(178c.790): CLR exception - code e0434352 (first chance)<br />
</code><br />
I changed the exception handling settings to stop on C++ exceptions (<code>sxe eh</code>) then ran again to see where things were going wrong. It stopped here:<br />
<code><br />
0:000> kp<br />
ChildEBP RetAddr<br />
0012d15c 79084c0f KERNEL32!RaiseException+0x53<br />
0012d194 793371be MSVCR100_CLR0400!_CxxThrowException+0x48<br />
0012d5e4 79455cae clr!EEFileLoadException::Throw+0x1a8<br />
0012d634 794558d2 clr!CompareTypeTokens+0x200<br />
0012d6b0 791b5c00 clr!IsTypeDefEquivalent+0x102<br />
0012d6d4 791b2ca8 <b>clr!MethodTableBuilder::CheckForTypeEquivalence</b>+0x94<br />
0012d7ac 791b27c9 clr!MethodTableBuilder::BuildMethodTableThrowing+0x60d<br />
0012d9a4 791a4578 clr!ClassLoader::CreateTypeHandleForTypeDefThrowing+0x88e<br />
</code><br />
Interesting. Notice how the call stack contains some .NET 4.0 specific methods relating to the new type equivalence feature. We&#8217;re hitting a new code path, which is consistent with the fact that running against a down-level CLR works.</p>
<p>After a bit more toing-and-froing, I discovered that the C++ exception is thrown when <code>clr!MDInternalRO::IsValidToken</code> returns an error. By disassembling the function we can see it&#8217;s just looking at various bits in the token value, and it decides that the value passed (0&#215;02000000) isn&#8217;t valid. Looking at the output from ildasm that token doesn&#8217;t appear anywhere. And if we add a dump of the value, we can see that it indeed doesn&#8217;t look like the other tokens: </p>
<pre>
0:000> bu clr!MDInternalRO::IsValidToken "dd esp+8 L1; g"
...
0012f5a8  02000001
0012f31c  06000001
0012f2c0  02000002
0012f0f4  02000002
0012ebe4  01000001
0012e944  23000001
...
0012d5f4  02000000
(18ec.1ec8): C++ EH exception - code e06d7363 (first chance)
</pre>
<h2>What&#8217;s the culprit?</h2>
<p>So it looks pretty conclusive; the DLL contains something that the CLR isn&#8217;t expecting. But what? It&#8217;s time to break out the oldest tool in the troubleshooting box: the binary chop!</p>
<p>Eventually I got the referenced DLL down to only a single simple construct. Can you guess what it is? A global literal value. A <em>real</em> global value, one that isn&#8217;t even part of a type. Crazy huh? In IL it looks like this:<br />
<code><br />
.field public static literal valuetype Test.MyEnum LiteralValue = int32(0x00000001)<br />
</code><br />
It&#8217;s a literal value of an enumerated type. That&#8217;s important: using a value of a simple type (say int32) does not provoke the error.</p>
<p>Now, I wasn&#8217;t even sure that this is a valid IL construct, but according to the ECMA IL spec, specifically <a href="http://jilc.sourceforge.net/ecma_p2_cil.shtml#_Toc524940530">partition II, section 15</a>, it is:</p>
<blockquote><p>The CLI also supports global fields, which are fields declared outside of any type definition. Global fields shall be static.</p></blockquote>
<p>So it looks like we&#8217;re not doing anything illegal, backed up by the fact that the .NET 2.0 CLR can make use of it without a problem.</p>
<p>Interestingly, there&#8217;s another aspect that influences whether this code path is hit. As mentioned above, type equivalence is intended for use with interop libraries. As such, it only kicks in if your referenced assembly is marked with the PrimaryInteropAssembly attribute, e.g.:</p>
<p><code><br />
  .custom instance void [mscorlib]System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute::.ctor(int32,int32) = ( 01 00 01 00 00 00 00 00 00 00 00 00 )<br />
</code></p>
<h2>The Fix?</h2>
<p>The issue is currently with Microsoft product support. Let&#8217;s see what they come up with; is it too esoteric for a hotfix&#8230;?</p>
<h2>The Repro</h2>
<p>Here&#8217;s some code and instructions on how to repro the problem.</p>
<ol>
<li>Build the IL into a DLL using ilasm.<br />
<code>"c:\WINNT\Microsoft.NET\Framework\v2.0.50727\ilasm.exe" /dll Test.il /output=Test.dll</code>
</li>
<li>Build the application into a .NET 4.0 EXE that references the DLL<br />
<code>"c:\winnt\Microsoft.NET\Framework\v4.0.30319\csc.exe" TestConsumer.cs /reference:Test.dll</code>
</li>
<li>Run the resulting <code>TestConsumer.exe</code> application and you&#8217;ll get the exception</li>
</ol>
<p><b>Test.il</b><br />
<code><br />
.assembly extern mscorlib<br />
{<br />
  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 )<br />
  .ver 2:0:0:0<br />
}<br />
.assembly Test<br />
{<br />
  .custom instance void [mscorlib]System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute::.ctor(int32,int32) = ( 01 00 01 00 00 00 00 00 00 00 00 00 )<br />
  .hash algorithm 0x00008004<br />
  .ver 1:0:0:0<br />
}<br />
.module Test.dll<br />
.imagebase 0x00400000<br />
.file alignment 0x00000200<br />
.stackreserve 0x00100000<br />
.subsystem 0x0003<br />
.corflags 0x00000001 </p>
<p>.field public static literal valuetype Test.MyEnum LiteralValue = int32(0x00000001)</p>
<p>.class public auto ansi sealed Test.MyEnum<br />
       extends [mscorlib]System.Enum<br />
{<br />
  .field public specialname rtspecialname int32 value__<br />
  .field public static literal valuetype Test.MyEnum Zero = int32(0x00000000)<br />
  .field public static literal valuetype Test.MyEnum One = int32(0x00000001)<br />
}<br />
</code><br />
<b>TestConsumer.cs</b></p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #FF0000;">class</span> X
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        var v <span style="color: #008000;">=</span> Test.<span style="color: #0000FF;">MyEnum</span>.<span style="color: #0000FF;">Zero</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2010/04/23/net-4-0-type-equivalence-causes-badimageformatexception/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Beware of using stack-based COM objects from .NET</title>
		<link>http://www.voyce.com/index.php/2010/01/21/beware-of-using-stack-based-com-objects-from-net/</link>
		<comments>http://www.voyce.com/index.php/2010/01/21/beware-of-using-stack-based-com-objects-from-net/#comments</comments>
		<pubDate>Thu, 21 Jan 2010 17:16:57 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[COM]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[WinDbg]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[mscorwks]]></category>
		<category><![CDATA[win32]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=618</guid>
		<description><![CDATA[COM objects that don't have the expected lifetime can cause chaos when combined with .NETs garbage collection system.]]></description>
			<content:encoded><![CDATA[<p>There are all sorts of nasty things to be aware of if you&#8217;re mixing reference-counted COM objects with garbage-collected .NET. For instance, if you&#8217;re implementing COM objects in C++ then you&#8217;re free to allocate them anywhere you like; on the heap or perhaps on the stack if you know they&#8217;re only used in some specific scope.</p>
<p>But what happens if during the lifetime of that stack based COM object, it gets used from .NET? A runtime callable wrapper (RCW) will be created around the object. And this RCW expects to be able to keep the underlying object alive by incrementing its reference count. Of course, the stack-based object will soon go out of scope, and regardless of its reference count the object will be destroyed and the pointer that the RCW contains will no longer be valid. It points into the stack, so when the RCW gets cleaned-up, the CLR will call via this pointer into memory that contains garbage and you&#8217;ll get something nasty like an access violation or illegal instruction exception. </p>
<p><span id="more-618"></span></p>
<p>It&#8217;s fairly easy to reproduce this to see where things go wrong. It can be useful to see where the CLR blows up, and how we can identify this as the cause.</p>
<p>Lets start by creating a simple pseudo-COM object that implements just the bare minimum to be usable:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">class</span> MyClass <span style="color: #008080;">:</span> <span style="color: #0000ff;">public</span> IUnknown
<span style="color: #008000;">&#123;</span>
<span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
	MyClass<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">:</span>l<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span><span style="color: #008000;">&#125;</span>
	STDMETHOD_<span style="color: #008000;">&#40;</span>ULONG, AddRef<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">return</span> InterlockedIncrement<span style="color: #008000;">&#40;</span><span style="color: #000040;">&amp;</span>l<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span>
	STDMETHOD_<span style="color: #008000;">&#40;</span>ULONG, Release<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">return</span> InterlockedDecrement<span style="color: #008000;">&#40;</span><span style="color: #000040;">&amp;</span>l<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span>
	STDMETHOD<span style="color: #008000;">&#40;</span>QueryInterface<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span>REFIID iid, <span style="color: #0000ff;">void</span> <span style="color: #000040;">**</span> ppvObject<span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span>
		<span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>iid <span style="color: #000080;">==</span> IID_IUnknown<span style="color: #008000;">&#41;</span>
		<span style="color: #008000;">&#123;</span>
			<span style="color: #000040;">*</span>ppvObject <span style="color: #000080;">=</span> <span style="color: #0000dd;">this</span><span style="color: #008080;">;</span>
			AddRef<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
                        <span style="color: #0000ff;">return</span> S_OK<span style="color: #008080;">;</span>
		<span style="color: #008000;">&#125;</span>
		<span style="color: #0000ff;">return</span> E_NOINTERFACE<span style="color: #008080;">;</span>
	<span style="color: #008000;">&#125;</span>
<span style="color: #0000ff;">private</span><span style="color: #008080;">:</span>
	<span style="color: #0000ff;">long</span> l<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></div></div>

<p>We&#8217;ll also need a COM visible .NET object that will use the object. It doesn&#8217;t actually need to be COM visible, but that&#8217;s the easiest way to access it from C++, in my opinion.</p>
<p>I&#8217;ve created the COM object in F#. It&#8217;s a trivial class that has a single interface, with a single method that takes the object we pass to it and prints its type. This is enough for the RCW to be created.</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;">Runtime</span><span style="color: #000080;">.</span><span style="color: #505090;">InteropServices</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">module</span> Module1 <span style="color: #000080;">=</span>
&nbsp;
    <span style="color: #000080;">&#91;</span><span style="color: #000080;">&lt;</span>ComVisible<span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">true</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">;</span> InterfaceType<span style="color: #000080;">&#40;</span>ComInterfaceType<span style="color: #000080;">.</span><span style="color: #505090;">InterfaceIsIUnknown</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&gt;</span><span style="color: #000080;">&#93;</span>
    <span style="color: #06c; font-weight: bold;">type</span> <span style="color: #06c; font-weight: bold;">public</span> IConsumer <span style="color: #000080;">=</span> 
        <span style="color: #06c; font-weight: bold;">abstract</span> <span style="color: #06c; font-weight: bold;">member</span> UseObject <span style="color: #000080;">:</span> o<span style="color: #000080;">:</span>obj <span style="color: #000080;">-&gt;</span> unit
&nbsp;
    <span style="color: #000080;">&#91;</span><span style="color: #000080;">&lt;</span>ComVisible<span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">true</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">;</span> ClassInterface<span style="color: #000080;">&#40;</span>ClassInterfaceType<span style="color: #000080;">.</span><span style="color: #505090;">None</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&gt;</span><span style="color: #000080;">&#93;</span>
    <span style="color: #06c; font-weight: bold;">type</span> <span style="color: #06c; font-weight: bold;">public</span> Consumer<span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
        <span style="color: #06c; font-weight: bold;">interface</span> IConsumer <span style="color: #06c; font-weight: bold;">with</span>
            <span style="color: #06c; font-weight: bold;">member</span> this<span style="color: #000080;">.</span><span style="color: #505090;">UseObject</span> <span style="color: #000080;">&#40;</span>o<span style="color: #000080;">:</span>obj<span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
                Console<span style="color: #000080;">.</span><span style="color: #505090;">WriteLine</span> <span style="color: #000080;">&#40;</span>sprintf <span style="color: #008080;">&quot;%A&quot;</span> <span style="color: #000080;">&#40;</span>o<span style="color: #000080;">.</span><span style="color: #505090;">GetType</span><span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span></pre></div></div>

<p>We can compile this into a DLL, then run regasm with the /tlb switch to generate a type library (TLB):</p>
<pre>
fsc -o:obj\Debug\testStackObjectsFs.dll Module1.fs
regasm /tlb:testStackObjectsFs.tlb testStackObjectsFs.dll
</pre>
<p>That can be #imported back into our test harness:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #339900;">#import &quot;testStackObjectsFs.tlb&quot;</span></pre></div></div>

<p>Now we&#8217;re ready to put together some code that creates an instance of our object on the stack and passes it to our .NET component:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">void</span> Foo<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
	<span style="color: #666666;">// Create an instance of our &quot;COM object&quot; on the stack</span>
	MyClass obj<span style="color: #008080;">;</span>
&nbsp;
	<span style="color: #666666;">// Create a managed object</span>
	testStackObjectsFs<span style="color: #008080;">::</span><span style="color: #007788;">IConsumerPtr</span> mgd<span style="color: #008000;">&#40;</span>__uuidof<span style="color: #008000;">&#40;</span>testStackObjectsFs<span style="color: #008080;">::</span><span style="color: #007788;">Consumer</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
	<span style="color: #666666;">// and pass our COM object to it</span>
	mgd<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>UseObject<span style="color: #008000;">&#40;</span>_variant_t<span style="color: #008000;">&#40;</span><span style="color: #000040;">&amp;</span>obj<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">int</span> _tmain<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> argc, _TCHAR<span style="color: #000040;">*</span> argv<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
	<span style="color: #666666;">// Initialise the COM runtime, for our purposes it doesn't</span>
	<span style="color: #666666;">// matter which threading model we use</span>
	CoInitializeEx<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">NULL</span>, COINIT_MULTITHREADED<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
	<span style="color: #666666;">// Call a separate function, to ensure stack-based objects</span>
	<span style="color: #666666;">// are out-of-scope on return.</span>
	Foo<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
	<span style="color: #666666;">// Wait for some input</span>
	_getch<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
	<span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Now, if you run this from within Visual Studio, if you&#8217;re vigilant (and you haven&#8217;t got your debugger set to stop on access violations), then you&#8217;ll notice this in the output window after the return statement executes:<br />
<code><br />
...<br />
The thread 'Win32 Thread' (0x15b0) has exited with code 11001 (0x2af9).<br />
The thread 'Win32 Thread' (0x1110) has exited with code 0 (0x0).<br />
<b>First-chance exception at 0x00850a2b in testStackObjects.exe: 0xC0000005: Access violation reading location 0x00850a2b.</b><br />
The thread 'DebuggerRCThread::ThreadProcStatic' (0x1534) has exited with code 0 (0x0).<br />
The thread 'RPC Callback Thread' (0x12b8) has exited with code 0 (0x0).<br />
...<br />
</code><br />
Lets ramp up WinDbg, attach to the process (that _getch comes in useful here) and find out what&#8217;s going on in a bit more detail.</p>
<p>If we let the app run to the point of failure in WinDbg, we can see that the CLR was in the act of shutting down when it caused the exception:<br />
<code><br />
0:002> kp<br />
ChildEBP RetAddr<br />
WARNING: Frame IP not in any known module. Following frames may be wrong.<br />
00dae3fc 79f4c1b5 0xe06ff8<br />
00dae450 79f4c26c mscorwks!ReleaseTransitionHelper+0x5f<br />
00dae494 79f4c2d0 mscorwks!SafeReleaseHelper+0x8c<br />
00dae4c8 79faaa01 mscorwks!SafeRelease+0x2f<br />
00dae4fc 79faa7c8 mscorwks!IUnkEntry::Free+0x68<br />
00dae510 79faa91d mscorwks!RCW::ReleaseAllInterfaces+0x18<br />
00dae540 79faa949 mscorwks!RCW::ReleaseAllInterfacesCallBack+0xbd<br />
00dae570 7a0792ac mscorwks!RCW::Cleanup+0x22<br />
00dae57c 7a079714 mscorwks!RCWCleanupList::ReleaseRCWListRaw+0x16<br />
00dae5ac 7a0797df mscorwks!RCWCleanupList::ReleaseRCWListInCorrectCtx+0xdf<br />
00dae5fc 79fdc140 mscorwks!RCWCleanupList::CleanupAllWrappers+0x77<br />
00dafe90 79fdc7aa mscorwks!RCWCache::ReleaseWrappersWorker+0x103<br />
00dafed8 79fd9f95 mscorwks!ReleaseRCWsInCaches+0x27<br />
00dafee0 79f3c76a mscorwks!InnerCoEEShutDownCOM+0x1e<br />
00daff14 79f92015 mscorwks!WKS::GCHeap::FinalizerThreadStart+0x1fc<br />
00daffb4 7c80b683 mscorwks!Thread::intermediateThreadProc+0x49<br />
00daffec 00000000 kernel32!BaseThreadStart+0x37<br />
</code><br />
Essentially it&#8217;s cleaning up the currently unused RCWs &#8211; including our malformed one &#8211; and as part of doing this, it&#8217;s calling Release on the underlying COM object, via the mscorwks!SafeRelease function. SafeRelease wraps the call to potentially (and definitely, in this case) dangerous unmanaged code with various exception handlers, enabling it to silently handle access violations. </p>
<p>If we run the app again, and this time break while it&#8217;s waiting for the keypress, before it attempts to clean up the RCWs, then we can examine the wrapper ourselves, using the approach I set out in <a href="http://www.voyce.com/index.php/2009/09/03/getting-iunknown-from-__comobject/">this post</a>.</p>
<p>List all of the untyped COM object wrappers:</p>
<pre>
0:002> !dumpheap -type System.__ComObject
 Address       MT     Size
<font color="blue"><b>01418628</b></font> 79306e60       16
total 1 objects
Statistics:
      MT    Count    TotalSize Class Name
79306e60        1           16 System.__ComObject
Total 1 objects
</pre>
<p>Use the address of the object to obtain its object header:<br />
<code><br />
0:002> dd <font color="blue">1418628</font>-4 L1<br />
01418624  0800<font color="red"><b>0002</b></font><br />
</code><br />
Use the syncblk identifier in the header to get the syncblk:</p>
<pre>
0:002> !syncblk <font color="red">2</font>
Index SyncBlock MonitorHeld Recursion Owning Thread Info  SyncBlock Owner
    2 <font color="darkgreen"><b>001e4d9c</b></font>            0         0 00000000     none    01418628 System.__ComObject
-----------------------------
Total           2
CCW             0
RCW             0
ComClassFactory 0
Free            0
</pre>
<p>Get the address of the RCW from the sync block:<br />
<code><br />
0:008> dd <font color="darkgreen">001e4d9c</font>+1c L1<br />
001e4db8  001e7dc8<br />
0:008> dd 001e7dc8+c L1<br />
001e7dd4  <font color="purple"><b>001de828</b></font><br />
</code><br />
And dump out the relevant bits of the RCW, the vtable of the object, at offset 0&#215;88, and the IUnknown pointer, at offset 0&#215;64:<br />
<code><br />
0:008> dds <font color="purple">001de828</font>+88 L1<br />
001de8b0  0041ac78 testStackObjects!MyClass::`vftable'<br />
0:008> dds <font color="purple">001de828</font>+64 L1<br />
001de88c  0012fe7c<br />
</code><br />
We can use <code>!address</code> to do a quick sanity check on the pointer and verify what we know to be the case; it&#8217;s stack memory:</p>
<pre>
0:008> !address 0012fe7c
    00030000 : 00124000 - 0000c000
                    Type     00020000 MEM_PRIVATE
                    Protect  00000004 PAGE_READWRITE
                    State    00001000 MEM_COMMIT
                    Usage    <b>RegionUsageStack</b>
                    Pid.Tid  490.13dc
</pre>
<p>If we run the app on again to the point that it fails, we can clearly see the address of the object being passed as an argument to <code>mscorwks!IUnkEntry::Free</code>.</p>
<p>So the moral of the story is; don&#8217;t pretend some arbitrary piece of stack memory is a real, reference counted COM object. You may be saving the cost of a heap allocation, but even if your app works OK today, it may not tomorrow when someone introduces a piece of .NET code somewhere in your object graph.</p>
<h4>Bonus Extra Content</h4>
<p>As a bonus tip, here are a couple of WinDbg breakpoints that can be used to dump each RCW as it&#8217;s created and destroyed.<br />
<code><br />
bu 79faa974 "dds @ecx L23; g"<br />
bu 79faa538 "dd @esp+20 L1; dds poi(@esp+20)+88 L1; g"<br />
</code></p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2010/01/21/beware-of-using-stack-based-com-objects-from-net/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>A WPF custom control in F#</title>
		<link>http://www.voyce.com/index.php/2009/12/14/a-wpf-custom-control-in-fsharp/</link>
		<comments>http://www.voyce.com/index.php/2009/12/14/a-wpf-custom-control-in-fsharp/#comments</comments>
		<pubDate>Mon, 14 Dec 2009 11:05:02 +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[Windows]]></category>
		<category><![CDATA[guidattribute fsharp]]></category>
		<category><![CDATA[wpf]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=459</guid>
		<description><![CDATA[What F# language and syntax features are required to implement a fundamentally object-oriented WPF custom control?]]></description>
			<content:encoded><![CDATA[<p>In the world of WPF with its powerful templating support, you&#8217;re much less likely to need to build a custom control from scratch than you are with legacy Windows GUI frameworks. For the vast majority of scenarios it&#8217;s possible to take an existing control and modify its appearance and behaviour to get what you need. However it is still possible and sometimes necessary to build something in code. The other day I was looking at creating one &#8211; using F# of course &#8211; and realised that a skeleton control serves as a good example of the kind of cross-paradigm features the language offers. They&#8217;re the kind of things that make it possible to use functional F# with inherently imperative .NET languages and frameworks like WPF.<br />
<span id="more-459"></span><br />
Let&#8217;s start by looking at the code for the control in its entirety, and then we&#8217;ll break it down bit-by-bit:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">type</span> <span style="color: #06c; font-weight: bold;">public</span> MyControl<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> ItemsControl<span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
&nbsp;
    <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> FooProperty <span style="color: #000080;">:</span> DependencyProperty
&nbsp;
    <span style="color: #06c; font-weight: bold;">static</span> <span style="color: #06c; font-weight: bold;">member</span> OnFooChanged <span style="color: #000080;">&#40;</span>dob<span style="color: #000080;">:</span>DependencyObject<span style="color: #000080;">&#41;</span> args <span style="color: #000080;">=</span>
        <span style="color: #000080;">&#40;</span>dob <span style="color: #000080;">:</span>?<span style="color: #000080;">&gt;</span> MyControl<span style="color: #000080;">&#41;</span><span style="color: #000080;">.</span><span style="color: #505090;">Update</span> <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
&nbsp;
    <span style="color: #000080;">&#91;</span><span style="color: #000080;">&lt;</span>system<span style="color: #000080;">.</span><span style="color: #505090;">ComponentModel</span><span style="color: #000080;">.</span><span style="color: #505090;">Bindable</span><span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">true</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&gt;</span><span style="color: #000080;">&#93;</span>
    <span style="color: #06c; font-weight: bold;">member</span> <span style="color: #06c; font-weight: bold;">public</span> this<span style="color: #000080;">.</span><span style="color: #505090;">Foo</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> string  <span style="color: #000080;">=</span> string <span style="color: #000080;">&#40;</span>base<span style="color: #000080;">.</span><span style="color: #505090;">GetValue</span><span style="color: #000080;">&#40;</span>MyControl<span style="color: #000080;">.</span><span style="color: #505090;">FooProperty</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span>
        <span style="color: #06c; font-weight: bold;">and</span>  set<span style="color: #000080;">&#40;</span>r <span style="color: #000080;">:</span> string<span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span> base<span style="color: #000080;">.</span><span style="color: #505090;">SetValue</span><span style="color: #000080;">&#40;</span>MyControl<span style="color: #000080;">.</span><span style="color: #505090;">FooProperty</span>, r<span style="color: #000080;">&#41;</span>
&nbsp;
    <span style="color: #06c; font-weight: bold;">override</span> this<span style="color: #000080;">.</span><span style="color: #505090;">OnPropertyChanged</span> <span style="color: #000080;">&#40;</span>args<span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
        <span style="color: #06c; font-weight: bold;">match</span> args<span style="color: #000080;">.</span><span style="color: #505090;">Property</span><span style="color: #000080;">.</span><span style="color: #505090;">Name</span> <span style="color: #06c; font-weight: bold;">with</span>
        <span style="color: #000080;">|</span> <span style="color: #008080;">&quot;Foo&quot;</span> <span style="color: #000080;">-&gt;</span> this<span style="color: #000080;">.</span><span style="color: #505090;">Update</span> <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</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: #06c; font-weight: bold;">member</span> <span style="color: #06c; font-weight: bold;">internal</span> this<span style="color: #000080;">.</span><span style="color: #505090;">Update</span> <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
        System<span style="color: #000080;">.</span><span style="color: #505090;">Diagnostics</span><span style="color: #000080;">.</span><span style="color: #505090;">Debug</span><span style="color: #000080;">.</span><span style="color: #505090;">WriteLine</span> <span style="color: #000080;">&#40;</span>sprintf <span style="color: #008080;">&quot;Updating %A&quot;</span> <span style="color: #000080;">&#40;</span>base<span style="color: #000080;">.</span><span style="color: #505090;">GetValue</span><span style="color: #000080;">&#40;</span>MyControl<span style="color: #000080;">.</span><span style="color: #505090;">FooProperty</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;">static</span> <span style="color: #06c; font-weight: bold;">do</span>
        <span style="color: #06c; font-weight: bold;">let</span> metadata <span style="color: #000080;">=</span> PropertyMetadata<span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">null</span>, PropertyChangedCallback <span style="color: #000080;">&#40;</span>MyControl<span style="color: #000080;">.</span><span style="color: #505090;">OnFooChanged</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">&#41;</span>
        MyControl<span style="color: #000080;">.</span><span style="color: #505090;">FooProperty</span> <span style="color: #000080;">&lt;-</span> DependencyProperty<span style="color: #000080;">.</span><span style="color: #505090;">Register</span><span style="color: #000080;">&#40;</span><span style="color: #008080;">&quot;Foo&quot;</span>, typeof<span style="color: #000080;">&lt;</span>string<span style="color: #000080;">&gt;</span>, typeof<span style="color: #000080;">&lt;</span>MyControl<span style="color: #000080;">&gt;</span>, metadata<span style="color: #000080;">&#41;</span></pre></div></div>

<h2>Constructor</h2>
<p>We don&#8217;t have one! Well, that&#8217;s not strictly true. There&#8217;s no per-instance set-up that we need to do here, so instead we have a default, parameter-less constructor implied by the &#8220;empty brackets&#8221; syntax in the type declaration. If we wanted to execute some code in the constructor, we could add the following:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">do</span>
        Debug<span style="color: #000080;">.</span><span style="color: #505090;">WriteLine</span> <span style="color: #008080;">&quot;Constructing.&quot;</span></pre></div></div>

<p>It&#8217;s also possible to add further constructors (perhaps parameterised differently) but when using WPF bear in mind that instances of your class will often be created from a XAML declaration, which generally uses the default constructor and then sets properties as required. Mutable objects: ug.</p>
<h2>Inheritance</h2>
<p>Our type derives from the WPF <code>ItemsControl</code> class using the <code>inherit</code> keyword. Of course, we&#8217;re still subject to the single-inheritance limit of .NET (not a bad thing, if you ask me &#8211; no more tortured object hierarchies):</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">type</span> <span style="color: #06c; font-weight: bold;">public</span> MyControl<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> ItemsControl<span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span></pre></div></div>

<p>Note that we have to include the empty brackets on the inherited type name, as this will be constructed implicitly when our derived class is constructed. We can access the inherited class from elsewhere in the code using the <code>base</code> keyword.</p>
<h2>Static members</h2>
<p>Dependency properties are a WPF construct that provide external storage of property values. They allow deep trees of objects to efficiently use lots of properties where they often have the default value, which is commonly the case in WPF. In order to use them with your class you have to do a few things, including creating a static value to hold the property and its metadata. We create a mutable static member for this:</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;">&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> FooProperty <span style="color: #000080;">:</span> DependencyProperty</pre></div></div>

<p>Why a mutable static value? If you&#8217;ve used F# already you might be aware that it&#8217;s also possible to declare an immutable static variable and its initial value in one shot with a <code>let</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">static</span> <span style="color: #06c; font-weight: bold;">let</span> FooProperty <span style="color: #000080;">=</span> DependencyProperty<span style="color: #000080;">.</span><span style="color: #505090;">RegisterProperty</span> <span style="color: #000080;">&#40;</span><span style="color: #008080;">&quot;Foo&quot;</span>, typeof<span style="color: #000080;">&lt;</span>string<span style="color: #000080;">&gt;</span>, typeof<span style="color: #000080;">&lt;</span>MyControl<span style="color: #000080;">&gt;</span><span style="color: #000080;">&#41;</span></pre></div></div>

<p>Unfortunately, this results in your DP being private. Although the CLR property is still accessible, anything that attempts to access the DP directly &#8211; for instance, code within the WPF libraries &#8211; won&#8217;t see it. This means you have to use the mutable style, which is unfortunate.</p>
<h2>Static methods</h2>
<p>We&#8217;ve declared a static member function that is used to receive notifications when our DP is changed (although it&#8217;s complete overkill in this example, because we&#8217;ve already declared our DP with metadata that tells it to notify us when it changes):</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">static</span> <span style="color: #06c; font-weight: bold;">member</span> OnFooChanged <span style="color: #000080;">&#40;</span>dob<span style="color: #000080;">:</span>DependencyObject<span style="color: #000080;">&#41;</span> args <span style="color: #000080;">=</span>
        <span style="color: #000080;">&#40;</span>dob <span style="color: #000080;">:</span>?<span style="color: #000080;">&gt;</span> MyControl<span style="color: #000080;">&#41;</span><span style="color: #000080;">.</span><span style="color: #505090;">Update</span> <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span></pre></div></div>

<p>As you&#8217;d expect, there&#8217;s no <code>this</code> parameter on the signature, a static member doesn&#8217;t have any implicit object instance to work on. Luckily the arguments to most event functions include the DependencyObject that raised the notification. That means we can downcast dynamically to our expected type (with <code>: ?&gt;</code>) and use it. Bear in mind that this is more like casting than <code>as</code> in C#, as it will throw an <code>InvalidCastException</code> at runtime rather than returning null.</p>
<h2>Properties</h2>
<p>In order for our dependency property to be easily accessible we can expose it as a plain old CLR property. The implementation of the getter and setter simply defers all of the actual work of storing and retrieving the value to the underlying dependency property.</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">member</span> <span style="color: #06c; font-weight: bold;">public</span> this<span style="color: #000080;">.</span><span style="color: #505090;">Foo</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> string  <span style="color: #000080;">=</span> string <span style="color: #000080;">&#40;</span>base<span style="color: #000080;">.</span><span style="color: #505090;">GetValue</span><span style="color: #000080;">&#40;</span>MyControl<span style="color: #000080;">.</span><span style="color: #505090;">FooProperty</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span>
        <span style="color: #06c; font-weight: bold;">and</span>  set<span style="color: #000080;">&#40;</span>r <span style="color: #000080;">:</span> string<span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span> base<span style="color: #000080;">.</span><span style="color: #505090;">SetValue</span><span style="color: #000080;">&#40;</span>MyControl<span style="color: #000080;">.</span><span style="color: #505090;">FooProperty</span>, r<span style="color: #000080;">&#41;</span></pre></div></div>

<p>Notice how we have to cast the <code>obj</code> returned from <code>GetValue</code> into the correct type. This is another example of having to bridge the gap between the dynamically typed WPF property system and F#&#8217;s static typing.</p>
<h2>Overridden members</h2>
<p>As well as providing new member functions and properties, we may need to override existing ones. Member functions marked <code>abstract</code> in the base class can be overridden using the <code>override</code> keyword:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">override</span> this<span style="color: #000080;">.</span><span style="color: #505090;">OnPropertyChanged</span> <span style="color: #000080;">&#40;</span>args<span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
        <span style="color: #06c; font-weight: bold;">match</span> args<span style="color: #000080;">.</span><span style="color: #505090;">Property</span><span style="color: #000080;">.</span><span style="color: #505090;">Name</span> <span style="color: #06c; font-weight: bold;">with</span>
        <span style="color: #000080;">|</span> <span style="color: #008080;">&quot;Foo&quot;</span> <span style="color: #000080;">-&gt;</span> this<span style="color: #000080;">.</span><span style="color: #505090;">Update</span> <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</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></pre></div></div>

<p>The F# compiler provides the same kind of checking that the C# compiler does, warning you if you inadvertantly hide a base class function by creating an override with the same name but not marking it with <code>override</code>.</p>
<h2>Static constructor</h2>
<p>As mentioned before, we use the static constructor to initialise our mutable static variables. The syntax is similar to the <code>do</code> syntax of a normal constructor, with the addition of the <code>static</code> keyword:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">static</span> <span style="color: #06c; font-weight: bold;">do</span>
        <span style="color: #06c; font-weight: bold;">let</span> metadata <span style="color: #000080;">=</span> PropertyMetadata<span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">null</span>, PropertyChangedCallback <span style="color: #000080;">&#40;</span>MyControl<span style="color: #000080;">.</span><span style="color: #505090;">OnFooChanged</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">&#41;</span>
        <span style="color: #000080;">...</span></pre></div></div>

<p>Static constructors are run once per class, regardless of how many instances of the class you have. WPF relies quite heavily on static, class-based functionality; mostly because a lot of what&#8217;s set-up is per-class configuration &#8211; it&#8217;s not going to change during the lifetime of the application &#8211; so you may find yourself doing a fair amount of work in a static constructor. </p>
<p>So, there&#8217;s a quick run around some of the object-oriented features of the F# language: classes, inheritance, instance constructors, overridden member functions, static member functions and constructors. You can see how using WPF means you lose some of the benefits of the F# language; notably immutability and static typing. If you&#8217;re an experienced functional programmer getting deep into creating WPF or Silverlight custom controls you may find yourself using these OO constructs more than you&#8217;d like. Although F# makes it relatively painless in practice, mixing this heavily object oriented style of programming with a functional approach can still be a little hard to stomach at times.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2009/12/14/a-wpf-custom-control-in-fsharp/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

