<?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</title>
	<atom:link href="http://www.voyce.com/index.php/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.voyce.com</link>
	<description>Programming and debugging tidbits</description>
	<lastBuildDate>Sat, 06 Mar 2010 17:39:22 +0000</lastBuildDate>
	
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Too busy to blog&#8230;!?</title>
		<link>http://www.voyce.com/index.php/2010/03/05/too-busy-to-blog/</link>
		<comments>http://www.voyce.com/index.php/2010/03/05/too-busy-to-blog/#comments</comments>
		<pubDate>Fri, 05 Mar 2010 22:42:41 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=694</guid>
		<description><![CDATA[Live has been getting in the way of blogging.]]></description>
			<content:encoded><![CDATA[<p>Yes I know, shocking isn&#8217;t it? Too busy doing work that pays the bills to blog about random things I find interesting or amusing. </p>
<p>So what&#8217;s been keeping me away from WordPress?</p>
<ul>
<li>Spending too much time in WinDbg tracking down .NET and COM memory issues.</li>
<li>Wanting to have a good look at Visual Studio 2010 and .NET 4.0 (though not as much as I&#8217;d like, yet)</li>
<li>Playing lots of <a href="http://www.amazon.com/gp/product/B002JTX5SO?ie=UTF8&#038;tag=wwwvoycecom-20&#038;linkCode=as2&#038;camp=1789&#038;creative=390957&#038;creativeASIN=B002JTX5SO">Bayonetta</a><img src="http://www.assoc-amazon.com/e/ir?t=wwwvoycecom-20&#038;l=as2&#038;o=1&#038;a=B002JTX5SO" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />, and some <a href="http://www.amazon.com/gp/product/B002CZ38KA?ie=UTF8&#038;tag=wwwvoycecom-20&#038;linkCode=as2&#038;camp=1789&#038;creative=390957&#038;creativeASIN=B002CZ38KA">Heavy Rain</a><img src="http://www.assoc-amazon.com/e/ir?t=wwwvoycecom-20&#038;l=as2&#038;o=1&#038;a=B002CZ38KA" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />.</li>
<li>Doing lots of internal demos of the WPF\F# GUI-building toolset we&#8217;ve been working on. Should be interesting, specially now <a href="http://blogs.msdn.com/lucabol/archive/2010/02/19/luca-bolognese-leaves-microsoft.aspx">Luca&#8217;s coming on board</a>.</li>
<li>Experimenting with iPad development</li>
</ul>
<p>Hopefully I&#8217;ll get the chance to write something about all of this soon. </p>
<div><table border=0 bgcolor=#ffffff> <td><iframe src='http://digg.com/api/diggthis.php?w=new&amp;u=http%3A%2F%2Fwww.voyce.com%2Findex.php%2F2010%2F03%2F05%2Ftoo-busy-to-blog%2F&amp;t=Too+busy+to+blog...%21%3F&amp;s=normal' height='80' width='52' frameborder='0' scrolling='no'></iframe></td></table></div><!-- Generated by Digg Digg plugin, 
    Author : Yong Mook Kim
    Website : http://www.mkyong.com/blog/digg-digg-wordpress-plugin/
	-->]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2010/03/05/too-busy-to-blog/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Where&#8217;s my window?</title>
		<link>http://www.voyce.com/index.php/2010/01/31/wheres-my-window/</link>
		<comments>http://www.voyce.com/index.php/2010/01/31/wheres-my-window/#comments</comments>
		<pubDate>Sun, 31 Jan 2010 20:06:30 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[Windows]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[hidden]]></category>
		<category><![CDATA[invisible]]></category>
		<category><![CDATA[missing]]></category>
		<category><![CDATA[screen]]></category>
		<category><![CDATA[win32]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=667</guid>
		<description><![CDATA[Where's my window gone? I'm sure I left it around here somewhere...]]></description>
			<content:encoded><![CDATA[<p>On Windows, if you regularly change screen resolution or size, perhaps by accessing a machine remotely, you might find some of your application windows are no longer visible; they&#8217;re positioned outside of the visible display area. If you can&#8217;t see the window, it can be a <i>little</i> difficult to use the application. How can you get that window back?<br />
<span id="more-667"></span><br />
In most cases &#8211; but only only on pre-Vista versions of Windows &#8211; it can be easily resolved by right clicking on the task bar icon for the application, selecting Move and then using the cursor keys. This makes the cursor &#8220;stick&#8221; to the caption of the window, and you can move the mouse (without clicking!) to bring it onto the screen. Clicking releases the window.</p>
<p>You can do it without the mouse, too. Just make sure the window is selected in the task bar (perhaps by using the Windows key and then tabbing to the appropraite icon), then hit Alt-Space, Alt-M, and then using the cursor keys.</p>
<p>The only problem is, some application developers choose to change the system menu &#8211; the menu visible from clicking the app&#8217;s icon in the top left, or by right-clicking the task bar icon &#8211; perhaps deciding for some insane reason not to include the standard Move option (as an aside, this breaks one of the fundamental tenets of usability: don&#8217;t change &#8211; or in this case, remove &#8211; existing, established behaviour). If this is the case, you can instead use a handful of lines of Windows API code to access the window and move it programatically. Here&#8217;s the entire code of a program that will do exactly that:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #339900;">#include &lt;windows.h&gt;</span>
<span style="color: #339900;">#include &lt;tchar.h&gt;</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: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>argc <span style="color: #000080;">&lt;</span> <span style="color: #0000dd;">2</span><span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span>
		_tprintf<span style="color: #008000;">&#40;</span>_T<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;usage: mover windowtitle<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
		<span style="color: #0000ff;">return</span> <span style="color: #000040;">-</span><span style="color: #0000dd;">1</span><span style="color: #008080;">;</span>
	<span style="color: #008000;">&#125;</span>
	HWND hwnd <span style="color: #000080;">=</span> FindWindow<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">NULL</span>, argv<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
	<span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>hwnd<span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span>
		SetWindowPos<span style="color: #008000;">&#40;</span>hwnd, HWND_TOP, <span style="color: #0000dd;">0</span>, <span style="color: #0000dd;">0</span>, <span style="color: #0000dd;">400</span>,<span style="color: #0000dd;">400</span>, <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
	<span style="color: #008000;">&#125;</span>
	<span style="color: #0000ff;">else</span>
		_tprintf<span style="color: #008000;">&#40;</span>_T<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;Unable to find window %s<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #008000;">&#41;</span>, argv<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#93;</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>Compile it up and you can use it as a handy little utility to move arbitrary top level windows, e.g. if you&#8217;ve got regedit running:<br />
<code><br />
mover "Registry Editor"<br />
</code><br />
The only tricky thing is finding the exact title of the window to use. Well, you wouldn&#8217;t want it to be <i>too</i> easy, would you?</p>
<div><table border=0 bgcolor=#ffffff> <td><iframe src='http://digg.com/api/diggthis.php?w=new&amp;u=http%3A%2F%2Fwww.voyce.com%2Findex.php%2F2010%2F01%2F31%2Fwheres-my-window%2F&amp;t=Where%27s+my+window%3F&amp;s=normal' height='80' width='52' frameborder='0' scrolling='no'></iframe></td></table></div><!-- Generated by Digg Digg plugin, 
    Author : Yong Mook Kim
    Website : http://www.mkyong.com/blog/digg-digg-wordpress-plugin/
	-->]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2010/01/31/wheres-my-window/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Why the Peggle mobile experience beats GTA</title>
		<link>http://www.voyce.com/index.php/2010/01/26/why-the-peggle-mobile-experience-beats-gta/</link>
		<comments>http://www.voyce.com/index.php/2010/01/26/why-the-peggle-mobile-experience-beats-gta/#comments</comments>
		<pubDate>Tue, 26 Jan 2010 00:27:21 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[Gaming]]></category>
		<category><![CDATA[Usability]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[games]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=637</guid>
		<description><![CDATA[Peggle and Grand Theft Auto: Chinatown Wars. Two fantastic and very different iPhone games, but how is your enjoyment of them affected by the platform on which they run?]]></description>
			<content:encoded><![CDATA[<p><div id="attachment_643" class="wp-caption alignleft" style="width: 74px"><img src="http://www.voyce.com/wp-content/uploads/2010/01/peggle_icon.png" alt="Peggle icon" title="peggle_icon" width="64" height="64" class="size-full wp-image-643" align="left" /><img src="http://www.voyce.com/wp-content/uploads/2010/01/gta_icon.png" alt="GTA icon" title="gta_icon" width="64" height="64" class="size-full wp-image-644" /><p class="wp-caption-text">Pegs vs Triads</p></div>I&#8217;ve had two very different iPhone gaming experiences over the last few weeks: <a href="http://itunes.apple.com/gb/app/peggle/id314303518?mt=8">Peggle</a> and <a href="http://itunes.apple.com/gb/app/grand-theft-auto-chinatown-wars/id344186162?mt=8">Grand Theft Auto: Chinatown Wars</a>. It&#8217;s safe to say I got completely addicted to Peggle, but when it arrived I couldn&#8217;t resist the temptation of having the GTA universe in my pocket too. After shelling out the almighty sum of £5.99 on the sandbox triad-&#8217;em-up, I discovered that there were many aspects of playing/using Peggle that make it a better fit on the iPhone than GTA. Let&#8217;s break down how these very different experiences manage the transition to a hand-held, &#8220;casual&#8221; gaming platform. What exactly does &#8220;usability&#8221; mean in this context?<br />
<span id="more-637"></span></p>
<h3>1. Minimise cost of entry/exit &#8211; Instant on, instant off</h3>
<p>If there&#8217;s one thing that most characterises the mobile gaming experience, it&#8217;s the difference in playing cycle frequency and duration. As this highly unscientific graph shows:<br />
<div id="attachment_664" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.voyce.com/wp-content/uploads/2010/01/gaming_graph1.png"><img src="http://www.voyce.com/wp-content/uploads/2010/01/gaming_graph1-300x149.png" alt="Gaming intensity over an 18 hour period" title="gaming_graph" width="300" height="149" class="size-medium wp-image-664" /></a><p class="wp-caption-text">Gaming intensity over an 18 hour period</p></div>Players of a console game are much more likely to be giving the game their full attention, for potentially extended time periods. As such we expect them to give back experientially; rousing scores, scene-setting cinematics. How well do GTA&#8217;s movie stylings transfer to the 3.5&#8243; screen? Fairly well, as it turns out.</p>
<p>Handheld games need to be able to be picked-up and played, and similarly, put-down, in a flash. It&#8217;s just not feasible to insist on finishing a mission, returning to a safe-house etc, before the game can be safely stopped. You don&#8217;t want to lose the last few minutes progress just because you&#8217;ve arrived at your destination. Peggle has a few wrinkles here, the only times it crashed on me was after unlocking the phone to continue a game, but generally it&#8217;s perfectly paced for snatched play; each ball lasts a few seconds, and each game only a few minutes. Furthermore when resuming a game you can instantly see the number of blue and orange pegs remaining and therefore gauge game progress at a glance. Having a free-roaming city to explore is a fantastic experience, but keeping track of where you are requires more mental effort/investment.</p>
<h3>2. Support restricted input &#8211; One-handed operation</h3>
<p><img src="http://www.voyce.com/wp-content/uploads/2010/01/peggle_screenshot-300x200.png" alt="peggle_screenshot" title="peggle_screenshot" width="300" height="200" class="alignleft size-medium wp-image-655" />Personally, I get a few good hours a week of gaming time on the tube. Unfortunately most of that is while hanging from the hand-rails amongst a crowd of other commuters. This one-handed playing style is completely incompatible with GTA&#8217;s control model; the driving requires one hand for the accelerator, brake etc, and another for the directional controls. The overall pacing of the game is also important; twitch gaming doesn&#8217;t fit well with being buffeted around on the underground, but board-game style pacing is largely unaffected.  </p>
<h3>3. Degrade output gracefully &#8211; Shhhhhh!</h3>
<p>GTA is most definitely a multi-sensory experience. The radio soundtrack that kicks in as you jump into a &#8216;jacked motor. The ambient sounds of the city as you stalk the sidewalks looking for unsuspecting victims to eviscerate. Peggle has its own rousing soundtrack of course, Ode to orange peg Joy, but it&#8217;s much more of an ancillary aspect of the game. You can safely turn it off and it&#8217;s not going to reduce your ability to play, or alter the play experience. The importance of this becomes apparent whilst enjoying a surreptitious few minutes of fun in, say, just for example, err, the toilets at work. Not that I would <i>ever</i> do that, obviously&#8230; </p>
<h3>4. Work with device restrictions &#8211; Physicality</h3>
<p><img src="http://www.voyce.com/wp-content/uploads/2010/01/gta_screenshot-300x200.png" alt="gta_screenshot" title="gta_screenshot" width="300" height="200" class="alignright size-medium wp-image-654" />One of the things I found most jarring about the translation of the GTA experience to the iPhone is the very thing that makes the iPhone what it is: the touch screen. It&#8217;s just odd not having the haptic feedback on a stick, especially when you&#8217;re virtually pushing a car round a tight corner, or trying to chase someone down the street. I just felt like I needed to feel the limits of the controls. Part of the reason for this is the fact that you&#8217;re essentially controlling physical objects directly, whereas Peggle is much more abstract &#8211; albeit fundamentally based on the concrete physical behaviour of a falling ball. </p>
<h4>&#8230;but which is best?</h4>
<p>The answer? Who knows! The fact is they&#8217;re completely different experiences, so it depends what you&#8217;re looking for. The thing about smartphones, portable gaming devices etc, is that people use them in a vast array of different environments and in very different ways. Personally I don&#8217;t want a console replacement, but I do enjoy console-like experiences on the go every once in a while. I&#8217;m willing to change the way I use the phone &#8211; at least temporarily &#8211; to accommodate that. But I also love a game that fits perfectly with the way I already use my device; especially if it happens to be incredibly addictive, with simple but emergent game-play. These days I&#8217;m a real casual gamer, having to grab what time I can between work and the family, so having something that I can enjoy in 30 second segments on my own terms is a real pleasure. </p>
<p>It will be interesting to see how developers, gaming and otherwise, deal with the different usability requirements of these emerging platforms. These factors could quickly become important differentiators in a crowded market.</p>
<div><table border=0 bgcolor=#ffffff> <td><iframe src='http://digg.com/api/diggthis.php?w=new&amp;u=http%3A%2F%2Fwww.voyce.com%2Findex.php%2F2010%2F01%2F26%2Fwhy-the-peggle-mobile-experience-beats-gta%2F&amp;t=Why+the+Peggle+mobile+experience+beats+GTA&amp;s=normal' height='80' width='52' frameborder='0' scrolling='no'></iframe></td></table></div><!-- Generated by Digg Digg plugin, 
    Author : Yong Mook Kim
    Website : http://www.mkyong.com/blog/digg-digg-wordpress-plugin/
	-->]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2010/01/26/why-the-peggle-mobile-experience-beats-gta/feed/</wfw:commentRss>
		<slash:comments>1</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>
<div><table border=0 bgcolor=#ffffff> <td><iframe src='http://digg.com/api/diggthis.php?w=new&amp;u=http%3A%2F%2Fwww.voyce.com%2Findex.php%2F2010%2F01%2F21%2Fbeware-of-using-stack-based-com-objects-from-net%2F&amp;t=Beware+of+using+stack-based+COM+objects+from+.NET&amp;s=normal' height='80' width='52' frameborder='0' scrolling='no'></iframe></td></table></div><!-- Generated by Digg Digg plugin, 
    Author : Yong Mook Kim
    Website : http://www.mkyong.com/blog/digg-digg-wordpress-plugin/
	-->]]></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>0</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>
<div><table border=0 bgcolor=#ffffff> <td><iframe src='http://digg.com/api/diggthis.php?w=new&amp;u=http%3A%2F%2Fwww.voyce.com%2Findex.php%2F2009%2F12%2F14%2Fa-wpf-custom-control-in-fsharp%2F&amp;t=A+WPF+custom+control+in+F%23&amp;s=normal' height='80' width='52' frameborder='0' scrolling='no'></iframe></td></table></div><!-- Generated by Digg Digg plugin, 
    Author : Yong Mook Kim
    Website : http://www.mkyong.com/blog/digg-digg-wordpress-plugin/
	-->]]></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>
		<item>
		<title>Don&#8217;t do anything in DllMain&#8230; Please</title>
		<link>http://www.voyce.com/index.php/2009/12/03/dont-do-anything-in-dllmain-please/</link>
		<comments>http://www.voyce.com/index.php/2009/12/03/dont-do-anything-in-dllmain-please/#comments</comments>
		<pubDate>Thu, 03 Dec 2009 23:27:13 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[Debugging]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[COM]]></category>
		<category><![CDATA[dll]]></category>
		<category><![CDATA[win32]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=554</guid>
		<description><![CDATA[Thinking of adding some code to your DLLs DllMain function? STOP!]]></description>
			<content:encoded><![CDATA[<p>Novice Windows programmers can often think that <code>DllMain</code> is a good place to get that one-time set-up and tear-down work done. It seems to offer an ideal opportunity to know when your DLL has just been loaded, and when it&#8217;s about to be unloaded. What better place to add all that expensive, complicated initialisation&#8230;? STOP! WAIT! Before you add anything in <code>DllMain</code>, make sure you understand what state the process will be in when it gets called. Once you know that, you may well change your mind&#8230;<br />
<span id="more-554"></span><br />
Firstly, take a look at <a href="http://www.microsoft.com/whdc/driver/kernel/DLL_bestprac.mspx">this page</a>. It does a pretty good job of ramming home the point that there&#8217;s very little that it&#8217;s safe to do in <code>DllMain</code>. Essentially this is because while the function&#8217;s being called, the OS is holding a process-wide lock that isn&#8217;t re-entrant. As such, if you do anything that causes a DLL to be loaded, a deadlock may occur. There are many, many things that may have a side-effect of loading a DLL; calling COM functions, creating threads etc.</p>
<p>This is such a common source of bugs, and such an important requirement, that from Vista onwards Microsoft introduced a new set of functions in the Windows API explicitly to support it: <a href="http://msdn.microsoft.com/en-us/library/aa363808(VS.85).aspx">One-Time Initialization</a>.</p>
<p>And even if you get away with doing naughty things in <code>DllMain</code> now, don&#8217;t think that it&#8217;ll stay that way forever. We got away with it for years, then when .NET came along it introduced all sorts of additional correctness checks. For instance, the Managed Debugging Assistant (MDA) in Visual Studio will shout loudly should you attempt to run managed code during <code>DllMain</code>.<br />
<code><br />
Managed Debugging Assistant 'LoaderLock' has detected a problem in 'C:\YourApp.vshost.exe'.<br />
Additional Information: Attempting managed execution inside OS Loader lock. Do not attempt to run managed code inside a DllMain or image initialization function since doing so can cause the application to hang.<br />
</code><br />
And it&#8217;s easier than you think to do so. For example, calling something as innocuous as <code>GetWindowText</code> can result in managed code being run. </p>
<p>How can you get around this?</p>
<p>One of the approaches I&#8217;ve used has been to make use of Win32 asynchronous procedure calls. Specifically you can call <a href="http://msdn.microsoft.com/en-us/library/ms684954(VS.85).aspx">QueueUserAPC</a> to add a function to the queue, and this can contain the initialisation you would&#8217;ve otherwise done in <code>DllMain</code>. </p>
<p>However there is significant gotcha regarding use of APCs: your function will not be called until the thread is in an &#8220;alertable wait state&#8221;. This means you (or some other code on the thread) need to call an alertable wait function such as <a href="http://msdn.microsoft.com/en-us/library/ms686307(VS.85).aspx"><code>SleepEx</code></a>, <a href="http://msdn.microsoft.com/en-us/library/ms687036(VS.85).aspx"><code>WaitForSingleObjectEx</code></a> and specify TRUE for the alertable parameter. </p>
<p>Once your APC is getting called successfully you&#8217;ll be in much better place; your code will be executed outside of the scope of the dreaded OS loader lock and you&#8217;ll be doing things by the book, hopefully avoiding all the potential pitfalls that lie in wait within <code>DllMain</code>. </p>
<div><table border=0 bgcolor=#ffffff> <td><iframe src='http://digg.com/api/diggthis.php?w=new&amp;u=http%3A%2F%2Fwww.voyce.com%2Findex.php%2F2009%2F12%2F03%2Fdont-do-anything-in-dllmain-please%2F&amp;t=Don%27t+do+anything+in+DllMain...+Please&amp;s=normal' height='80' width='52' frameborder='0' scrolling='no'></iframe></td></table></div><!-- Generated by Digg Digg plugin, 
    Author : Yong Mook Kim
    Website : http://www.mkyong.com/blog/digg-digg-wordpress-plugin/
	-->]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2009/12/03/dont-do-anything-in-dllmain-please/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generating and plotting random numbers</title>
		<link>http://www.voyce.com/index.php/2009/11/24/generating-and-plotting-random-numbers/</link>
		<comments>http://www.voyce.com/index.php/2009/11/24/generating-and-plotting-random-numbers/#comments</comments>
		<pubDate>Tue, 24 Nov 2009 23:44:55 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Finance]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=562</guid>
		<description><![CDATA[An example of generating random numbers in F# and visualising their distribution using the WPF charting control.]]></description>
			<content:encoded><![CDATA[<p>For a while now I&#8217;ve been planning to write a blog post about pricing financial instruments using Monte Carlo techniques in F#. As part of this I needed to generate normally distributed random numbers, and while putting together the code to do it I realised it was interesting enough to warrant its own post.</p>
<p>I&#8217;m making use of a few F#/.NET idioms to make the process easier. For instance, sequences (.NET&#8217;s <code>IEnumerable</code>) are used as the source of uniformly distributed random numbers. Also, to verify that the resulting numbers are actually normally distributed, we can easily use existing WPF/silverlight controls to visualise the values direct from within Visual Studio, in a manner similar to <a href="http://www.voyce.com/index.php/2009/06/26/black-scholes-option-pricing-using-fsharp-and-wpf/">this previous post</a> &#8211; but without having to write the plotting code ourselves.<br />
<span id="more-562"></span></p>
<h3>Implementation</h3>
<p>So firstly, we create the random number stream:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">let</span> rr <span style="color: #000080;">=</span> System<span style="color: #000080;">.</span><span style="color: #505090;">Random</span><span style="color: #000080;">&#40;</span>System<span style="color: #000080;">.</span><span style="color: #505090;">DateTime</span><span style="color: #000080;">.</span><span style="color: #505090;">Now</span><span style="color: #000080;">.</span><span style="color: #505090;">Minute</span><span style="color: #000080;">&#41;</span>
<span style="color: #06c; font-weight: bold;">let</span> rands <span style="color: #000080;">=</span> seq <span style="color: #000080;">&#123;</span> <span style="color: #06c; font-weight: bold;">while</span> <span style="color: #06c; font-weight: bold;">true</span> <span style="color: #06c; font-weight: bold;">do</span> <span style="color: #06c; font-weight: bold;">yield</span> rr<span style="color: #000080;">.</span><span style="color: #505090;">NextDouble</span><span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">&#125;</span></pre></div></div>

<p>As you can see <code>rands</code> is an infinite sequence. As such, you should be wary of the &#8220;eager&#8221; functions from the Seq module that attempt to consume the entire sequence at once, they&#8217;ll obviously cause a problem here. Also notice that I&#8217;ve picked a somewhat dubious seed for the random number generator, as this is only for demonstration purposes.</p>
<p>In order to obtain normally distributed random numbers I&#8217;m using the <a href="http://en.wikipedia.org/wiki/Box–Muller_transform">Box-Muller</a> transform. I started off with an implementation transcribed from VBA (from <a href="http://www.amazon.com/gp/product/0470319585?ie=UTF8&#038;tag=wwwvoycecom-20&#038;linkCode=as2&#038;camp=1789&#038;creative=9325&#038;creativeASIN=0470319585">Wilmott</a><img src="http://www.assoc-amazon.com/e/ir?t=wwwvoycecom-20&#038;l=as2&#038;o=1&#038;a=0470319585" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /> et al) &#8211; yes, yes, I know &#8211; but of course this used mutable references. Not nice. So I reworked it a little to use <code>Seq.pick</code>, which takes items from the sequence while a predicate returns <code>None</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">let</span> boxMuller <span style="color: #06c; font-weight: bold;">_</span> <span style="color: #000080;">=</span>
    <span style="color: #06c; font-weight: bold;">let</span> <span style="color: #000080;">&#40;</span>x,dist<span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span> 
        rands
        <span style="color: #000080;">|&gt;</span> Seq<span style="color: #000080;">.</span><span style="color: #505090;">pick</span> <span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">fun</span> x <span style="color: #000080;">-&gt;</span>
            <span style="color: #06c; font-weight: bold;">let</span> x <span style="color: #000080;">=</span> <span style="color: #c6c;">2.0</span> <span style="color: #000080;">*</span> x <span style="color: #000080;">-</span> <span style="color: #c6c;">1.0</span>
            <span style="color: #06c; font-weight: bold;">let</span> y <span style="color: #000080;">=</span> <span style="color: #c6c;">2.0</span> <span style="color: #000080;">*</span> <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#40;</span>Seq<span style="color: #000080;">.</span><span style="color: #505090;">take</span> <span style="color: #c6c;">1</span> rands<span style="color: #000080;">&#41;</span> <span style="color: #000080;">|&gt;</span> Seq<span style="color: #000080;">.</span><span style="color: #505090;">hd</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">-</span> <span style="color: #c6c;">1.0</span>
            <span style="color: #06c; font-weight: bold;">match</span> <span style="color: #000080;">&#40;</span>x <span style="color: #000080;">*</span> x <span style="color: #000080;">+</span> y <span style="color: #000080;">*</span> y<span style="color: #000080;">&#41;</span> <span style="color: #06c; font-weight: bold;">with</span>
                <span style="color: #000080;">|</span> dist <span style="color: #06c; font-weight: bold;">when</span> dist <span style="color: #000080;">&lt;</span> <span style="color: #c6c;">1.0</span> <span style="color: #000080;">-&gt;</span> Some <span style="color: #000080;">&#40;</span>x,dist<span style="color: #000080;">&#41;</span>
                <span style="color: #000080;">|</span> dist <span style="color: #000080;">-&gt;</span> None
            <span style="color: #000080;">&#41;</span> 
    x <span style="color: #000080;">*</span> Math<span style="color: #000080;">.</span><span style="color: #505090;">Sqrt</span><span style="color: #000080;">&#40;</span><span style="color: #000080;">-</span><span style="color: #c6c;">2.0</span> <span style="color: #000080;">*</span> Math<span style="color: #000080;">.</span><span style="color: #505090;">Log</span><span style="color: #000080;">&#40;</span>dist<span style="color: #000080;">&#41;</span> <span style="color: #000080;">/</span> dist<span style="color: #000080;">&#41;</span></pre></div></div>

<p>It&#8217;s not particularly efficient as we&#8217;re consuming two uniform numbers to generate one normal one &#8211; hence the additional Seq.take within the pick. Of course we could change the function to return the 2 generated numbers as an extra element in the tuple.</p>
<p>Next, let&#8217;s generate some numbers, and get them in a suitable form to display:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">let</span> makeData <span style="color: #06c; font-weight: bold;">_</span> <span style="color: #000080;">=</span>
    Seq<span style="color: #000080;">.</span><span style="color: #505090;">init</span> <span style="color: #c6c;">100000</span> boxMuller
    <span style="color: #000080;">|&gt;</span> Seq<span style="color: #000080;">.</span><span style="color: #505090;">countBy</span> <span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">fun</span> d <span style="color: #000080;">-&gt;</span> 
        <span style="color: #06c; font-weight: bold;">let</span> d <span style="color: #000080;">=</span> decimal d
        Math<span style="color: #000080;">.</span><span style="color: #505090;">Round</span><span style="color: #000080;">&#40;</span>d, <span style="color: #c6c;">1</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span>
    <span style="color: #000080;">|&gt;</span> Seq<span style="color: #000080;">.</span><span style="color: #505090;">sortBy</span> fst</pre></div></div>

<p>We initialise a sequence with an arbitrary amount of numbers (100000, enough to get a good distribution, hopefully), then use <code>Seq.countBy</code> to do a naive grouping that allows us to see how the numbers are distributed, i.e. counting how many numbers fit in each 0.10 bucket. We then sort the output by bucket. </p>
<h3>Visualisation</h3>
<p>Now we can display what we&#8217;ve got. We can create a simple WPF object-model using imperative code, including the very useful chart control from the WpfToolkit. The chart control enables us to add a series and set our <code>seq&lt;decimal * float&gt;</code> directly as the series ItemsSource, which is the standard way to specify the items for a collection control. If you specify the tuple <code>Item1</code> and <code>Item2</code> properties for the bindings, WPF will be able to access the data from each element, and that&#8217;s all you need.</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">let</span> series <span style="color: #000080;">=</span> 
        ColumnSeries<span style="color: #000080;">&#40;</span>
            IndependentValueBinding <span style="color: #000080;">=</span> Data<span style="color: #000080;">.</span><span style="color: #505090;">Binding</span><span style="color: #000080;">&#40;</span><span style="color: #008080;">&quot;Item1&quot;</span><span style="color: #000080;">&#41;</span>,
            DependentValueBinding <span style="color: #000080;">=</span> Data<span style="color: #000080;">.</span><span style="color: #505090;">Binding</span><span style="color: #000080;">&#40;</span><span style="color: #008080;">&quot;Item2&quot;</span><span style="color: #000080;">&#41;</span>,
            ItemsSource <span style="color: #000080;">=</span> makeData <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span>
    <span style="color: #06c; font-weight: bold;">let</span> chart <span style="color: #000080;">=</span> Chart<span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
    chart<span style="color: #000080;">.</span><span style="color: #505090;">Series</span><span style="color: #000080;">.</span><span style="color: #505090;">Add</span> series
    Window<span style="color: #000080;">&#40;</span>
        Name<span style="color: #000080;">=</span><span style="color: #008080;">&quot;Plot&quot;</span>,
        Title<span style="color: #000080;">=</span><span style="color: #008080;">&quot;Normally distributed random numbers&quot;</span>,
        Width<span style="color: #000080;">=</span><span style="color: #c6c;">900.0</span>,
        Height<span style="color: #000080;">=</span><span style="color: #c6c;">700.0</span>,
        Content<span style="color: #000080;">=</span>chart,
        Visibility<span style="color: #000080;">=</span>Visibility<span style="color: #000080;">.</span><span style="color: #505090;">Visible</span><span style="color: #000080;">&#41;</span></pre></div></div>

<p>Here&#8217;s the resulting output:<br />
<img src="http://www.voyce.com/wp-content/uploads/2009/11/dist-300x233.png" alt="dist" title="dist" width="300" height="233" class="alignleft size-medium wp-image-576" />As I&#8217;ve mentioned before, this is a fantastically immediate way of doing numerical development in Visual Studio. You can enter all of this code directly into F# interactive within VS, iterate, and quickly see the effect that your changes have. It&#8217;s just as interactive as using the graph features in Excel, and the resulting code is much more easily reusable.</p>
<p><span style="visibility:hidden"> XD5RRV3XDNHN </span><br />
<script type="text/javascript" src="http://www.assoc-amazon.com/s/link-enhancer?tag=wwwvoycecom-20&#038;o=1">
</script><br />
<noscript><br />
    <img src="http://www.assoc-amazon.com/s/noscript?tag=wwwvoycecom-20" alt="" /><br />
</noscript></p>
<div><table border=0 bgcolor=#ffffff> <td><iframe src='http://digg.com/api/diggthis.php?w=new&amp;u=http%3A%2F%2Fwww.voyce.com%2Findex.php%2F2009%2F11%2F24%2Fgenerating-and-plotting-random-numbers%2F&amp;t=Generating+and+plotting+random+numbers&amp;s=normal' height='80' width='52' frameborder='0' scrolling='no'></iframe></td></table></div><!-- Generated by Digg Digg plugin, 
    Author : Yong Mook Kim
    Website : http://www.mkyong.com/blog/digg-digg-wordpress-plugin/
	-->]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2009/11/24/generating-and-plotting-random-numbers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Programming is like a bad analogy</title>
		<link>http://www.voyce.com/index.php/2009/11/11/programming-is-like-a-bad-analogy/</link>
		<comments>http://www.voyce.com/index.php/2009/11/11/programming-is-like-a-bad-analogy/#comments</comments>
		<pubDate>Wed, 11 Nov 2009 00:19:22 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[Rant]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www2.voyce.com/?p=388</guid>
		<description><![CDATA[The joy of programming can be a difficult thing to describe. I take a look at some of the bizarre things people have compared it to.]]></description>
			<content:encoded><![CDATA[<p>The <a href="<a href="http://www.amazon.com/gp/product/1430219483?ie=UTF8&#038;tag=wwwvoycecom-20&#038;linkCode=as2&#038;camp=1789&#038;creative=9325&#038;creativeASIN=1430219483">joy of programming</a><img src="http://www.assoc-amazon.com/e/ir?t=wwwvoycecom-20&#038;l=as2&#038;o=1&#038;a=1430219483" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /> is hard for anyone to precisely define. At least, it&#8217;s hard for programmers to define, and seeing as nobody else understands what the hell it is anyway, that&#8217;s pretty much the same thing. However a few people on the interweb have tried quite hard to describe just what the feeling of developing software is by comparing it to things in &#8220;the real world&#8221;.</p>
<p>A quick google reveals some of the funny, interesting and downright weird things that people have compared programming to. Let&#8217;s take a closer look at some of them&#8230;<br />
<span id="more-398"></span></p>
<h3>The Classics</h3>
<p>&#8220;Programming is like sex&#8221;<br />
The most common version of this is, of course, that &#8220;One mistake and you have to support it for the rest of your life&#8221;. Very true. Unless you can manage to change jobs every six months, and then it&#8217;s more like &#8220;You can have lots of fun and then leave somebody else to clear up the mess&#8221;. There are lots of other variations too, including the controversial: &#8220;Sometimes you have to pay a lot of money to get someone who&#8217;s good at it&#8221;. </p>
<p>&#8220;Programming is like <a href="http://compsci.ca/blog/programming-is-like-lego/">LEGO</a>&#8221;<br />
<img src="http://www.voyce.com/wp-content/uploads/2009/11/lego.png" alt="lego" title="lego" width="150" height="150" class="alignleft size-full wp-image-531" />Hmm. As far as I can see this just means that, yes, you can put the pieces together in any way you like, but nothing you make will look <em>quite</em> as good as the thing you make by following the instructions. The impression of infinite freedom is an illusion. And if you&#8217;re not careful you&#8217;ll end up losing important bits down the back of the sofa or hoovering them up.</p>
<p>And, hang on, if it is like Lego, then how come we&#8217;re always talking about programming &#8220;glue&#8221;?</p>
<p>&#8220;Programming is like <a href="http://ebersys.blogspot.com/2009/07/programming-is-like-chess.html">chess</a>&#8221;<br />
Not sure about this one. The biggest similarity I can see is that a lot of Russians are quite good at it. </p>
<p>Or maybe you could compare the interminably long games with the average duration of an enterprise software project? In fact, maybe having a <a href="http://en.wikipedia.org/wiki/Game_clock">chess clock</a> would make pair programming more fun; you get 30 seconds to write a line of code before it&#8217;s the other&#8217;s turn.</p>
<h3>The Outliers</h3>
<p>&#8220;Programming is like <a href="http://winpdb.org/2009/07/ice-programming/">Ice Sculpting</a>&#8221;<br />
What?! This has to be one of the most bizarre comparisons. I mean, yeah, it makes my hands really cold too. And my coworkers keep asking me why I bring that razor-sharp <a href="http://en.wikipedia.org/wiki/Ice_pick">ice pick</a> into the office on code review days.</p>
<p>&#8220;Programming is like <a href="http://www.independentdeveloper.com/archive/2009/03/17/programming-is-like-a-dream">a dream</a>&#8221;<br />
Unfortunately sometimes it&#8217;s like a really bad dream, the kind that you get from falling asleep on your keyboard during your afternoon sugar-low, dribbling on your mouse and getting an imprint of the enter key on your forehead. The kind where you wake up screaming after a nightmare about finding a bug in a 600-line long function with one-letter variable names and no comments. Only to find it&#8217;s not a dream after all, but where you will spend the majority of your waking hours for the next six months.</p>
<p>But of course, it can also be the kind of dream where you&#8217;re so far in the zone that you feel like you&#8217;re flying, effortlessly gliding over the terrain, appreciating the bigger-picture before swooping down into the details and watching how everything meshes beautifully together. Ahhh. </p>
<p>But it&#8217;s probably not the, erm, y&#8217;know, <em>other</em> type of dream. </p>
<p>&#8220;Programming is like <a href="http://www.gameproducer.net/2006/03/03/sometimes-programming-is-like-playing-an-adventure-game/">an adventure game</a>&#8221;<br />
<img src="http://www.voyce.com/wp-content/uploads/2009/11/zork_text1.png" alt="zork_text" title="zork_text" width="150" height="150" class="alignleft size-full wp-image-535" />Yes indeed. I often find myself having to go back over ground I&#8217;ve already covered, in order to perform repetitive and mundane tasks purely so I can level up (I think it&#8217;s known as &#8220;getting promoted&#8221;).</p>
<p>Sometimes I think that compiler writers treat their error messages as some kind of sadistic text-based game:</p>
<p><code>You are in an open field west of a big white house with a boarded front door. There is an unterminated string constant to the west, and an undefined external symbol to the east. There is a header file on the floor in front of you.<br />
&gt; include header<br />
You include the header. You are in a forest with incredibly long STL error messages all around.<br />
</code></p>
<p>On a serious note, I think part of the reason programming is so difficult to pin-down is because it requires such disparate skills; a combination of creative, intuitive right-brainedness and the logical, analytical left. People can take a lot of different things away from it depending on where they start from. </p>
<p>Anyway, that&#8217;s my selection of gems. Got any other interesting ones?</p>
<div><table border=0 bgcolor=#ffffff> <td><iframe src='http://digg.com/api/diggthis.php?w=new&amp;u=http%3A%2F%2Fwww.voyce.com%2Findex.php%2F2009%2F11%2F11%2Fprogramming-is-like-a-bad-analogy%2F&amp;t=Programming+is+like+a+bad+analogy&amp;s=normal' height='80' width='52' frameborder='0' scrolling='no'></iframe></td></table></div><!-- Generated by Digg Digg plugin, 
    Author : Yong Mook Kim
    Website : http://www.mkyong.com/blog/digg-digg-wordpress-plugin/
	-->]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2009/11/11/programming-is-like-a-bad-analogy/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Pinned DataTips in Visual Studio 2010 Beta 2</title>
		<link>http://www.voyce.com/index.php/2009/11/02/pinned-datatips-in-visual-studio-2010-beta-2/</link>
		<comments>http://www.voyce.com/index.php/2009/11/02/pinned-datatips-in-visual-studio-2010-beta-2/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 23:59:38 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[Debugging]]></category>
		<category><![CDATA[Usability]]></category>
		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=511</guid>
		<description><![CDATA[I&#8217;ve just noticed a nice little feature in Visual Studio 2010 Beta 2: pinned DataTips. Values displayed in the debugger as you hover over a variable can now be pinned in place and remain aligned with the source. They can even have annotations added&#8230; Tasty!
 ]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.voyce.com/wp-content/uploads/2009/11/vs2010_pinned_datatips.png"><img src="http://www.voyce.com/wp-content/uploads/2009/11/vs2010_pinned_datatips-300x42.png" alt="vs2010_pinned_datatips" title="vs2010_pinned_datatips" width="300" height="42" class="alignleft size-medium wp-image-512" /></a>I&#8217;ve just noticed a nice little feature in Visual Studio 2010 Beta 2: pinned DataTips. Values displayed in the debugger as you hover over a variable can now be pinned in place and remain aligned with the source. They can even have annotations added&#8230; Tasty!</p>
<div><table border=0 bgcolor=#ffffff> <td><iframe src='http://digg.com/api/diggthis.php?w=new&amp;u=http%3A%2F%2Fwww.voyce.com%2Findex.php%2F2009%2F11%2F02%2Fpinned-datatips-in-visual-studio-2010-beta-2%2F&amp;t=Pinned+DataTips+in+Visual+Studio+2010+Beta+2&amp;s=normal' height='80' width='52' frameborder='0' scrolling='no'></iframe></td></table></div><!-- Generated by Digg Digg plugin, 
    Author : Yong Mook Kim
    Website : http://www.mkyong.com/blog/digg-digg-wordpress-plugin/
	-->]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2009/11/02/pinned-datatips-in-visual-studio-2010-beta-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Comparing lambdas in C++ and F#</title>
		<link>http://www.voyce.com/index.php/2009/10/23/comparing-lambdas-in-c-and-f/</link>
		<comments>http://www.voyce.com/index.php/2009/10/23/comparing-lambdas-in-c-and-f/#comments</comments>
		<pubDate>Fri, 23 Oct 2009 19:51:27 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[F#]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[c++]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=461</guid>
		<description><![CDATA[Lambdas in C++ and F#: compare and contrast.]]></description>
			<content:encoded><![CDATA[<p>The other day someone pointed me to the new <a href="http://msdn.microsoft.com/en-us/library/dd293608(VS.100).aspx">MSDN article on C++ lambdas</a> in Visual Studio 2010. Interesting. C++0x has been a long time coming, but in my opinion anything that makes C++ usable at a higher level of abstraction is a good thing. There&#8217;s nothing wrong with a little abstraction, as long as you can get to the fundamentals if you need to. Otherwise you wouldn&#8217;t be using C++, would you?</p>
<p>But one of the things I couldn&#8217;t get over from that article is the verbosity. I&#8217;ve just got too used to the succintness of F#. I know this is only example code, so it&#8217;s intended to demonstrate usage, but the whole point of lambdas is to reduce boilerplate and make the intent of your code more obvious. So, let&#8217;s compare the C++0x implementation with the F# version.<br />
<span id="more-461"></span><br />
Here&#8217;s the C++ version, with the comments removed (including the &#8220;increment the counter&#8221; comment from the original article&#8230; Oh, please):</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #339900;">#include &lt;algorithm&gt;</span>
<span style="color: #339900;">#include &lt;iostream&gt;</span>
<span style="color: #339900;">#include &lt;vector&gt;</span>
<span style="color: #0000ff;">using</span> <span style="color: #0000ff;">namespace</span> std<span style="color: #008080;">;</span>
&nbsp;
<span style="color: #0000ff;">int</span> main<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
   vector<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">int</span><span style="color: #000080;">&gt;</span> v<span style="color: #008080;">;</span>
   <span style="color: #0000ff;">for</span> <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> i <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span> i <span style="color: #000080;">&lt;</span> <span style="color: #0000dd;">10</span><span style="color: #008080;">;</span> <span style="color: #000040;">++</span>i<span style="color: #008000;">&#41;</span>
   <span style="color: #008000;">&#123;</span>
      v.<span style="color: #007788;">push_back</span><span style="color: #008000;">&#40;</span>i<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
   <span style="color: #008000;">&#125;</span>
&nbsp;
   <span style="color: #0000ff;">int</span> evenCount <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
   for_each<span style="color: #008000;">&#40;</span>v.<span style="color: #007788;">begin</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>, v.<span style="color: #007788;">end</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>, <span style="color: #008000;">&#91;</span><span style="color: #000040;">&amp;</span>evenCount<span style="color: #008000;">&#93;</span> <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> n<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
      <span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> n<span style="color: #008080;">;</span>
&nbsp;
      <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>n <span style="color: #000040;">%</span> <span style="color: #0000dd;">2</span> <span style="color: #000080;">==</span> <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span>
      <span style="color: #008000;">&#123;</span>
         <span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot; is even &quot;</span> <span style="color: #000080;">&lt;&lt;</span> endl<span style="color: #008080;">;</span>
&nbsp;
         evenCount<span style="color: #000040;">++</span><span style="color: #008080;">;</span>
      <span style="color: #008000;">&#125;</span>
      <span style="color: #0000ff;">else</span>
      <span style="color: #008000;">&#123;</span>
         <span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot; is odd &quot;</span> <span style="color: #000080;">&lt;&lt;</span> endl<span style="color: #008080;">;</span>
      <span style="color: #008000;">&#125;</span>
   <span style="color: #008000;">&#125;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
   <span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;There are &quot;</span> <span style="color: #000080;">&lt;&lt;</span> evenCount <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot; even numbers in the vector.&quot;</span> <span style="color: #000080;">&lt;&lt;</span> endl<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>As well as the verbosity, notice the weird syntax used to capture the <code>evenCount</code> variable.</p>
<p>Without further ado, here&#8217;s an F# version &#8211; not a definitive one necessarily &#8211; that returns the value rather than doing nasty side-effecting IO by printing it out to the screen:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">seq <span style="color: #000080;">&#123;</span> 0<span style="color: #000080;">..</span>9 <span style="color: #000080;">&#125;</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> e <span style="color: #000080;">-&gt;</span> e <span style="color: #000080;">%</span> <span style="color: #c6c;">2</span> <span style="color: #000080;">=</span> <span style="color: #c6c;">0</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">|&gt;</span> Seq<span style="color: #000080;">.</span><span style="color: #505090;">length</span></pre></div></div>

<p>If you want to make it a bit more like the original code, you can add back the  <code>printf</code>s, and lay it out a bit more logically:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">let</span> count <span style="color: #000080;">=</span>
    seq <span style="color: #000080;">&#123;</span> 0<span style="color: #000080;">..</span>9 <span style="color: #000080;">&#125;</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> count e <span style="color: #000080;">-&gt;</span>
        <span style="color: #06c; font-weight: bold;">match</span> e <span style="color: #000080;">%</span> <span style="color: #c6c;">2</span> <span style="color: #06c; font-weight: bold;">with</span>
        <span style="color: #000080;">|</span> <span style="color: #c6c;">0</span> <span style="color: #000080;">-&gt;</span> printf <span style="color: #008080;">&quot;%d is even<span style="color: #008080; font-weight: bold;">\n</span>&quot;</span> e<span style="color: #000080;">;</span> count <span style="color: #000080;">+</span> <span style="color: #c6c;">1</span>
        <span style="color: #000080;">|</span> <span style="color: #06c; font-weight: bold;">_</span> <span style="color: #000080;">-&gt;</span> printf <span style="color: #008080;">&quot;%d is odd<span style="color: #008080; font-weight: bold;">\n</span>&quot;</span> e<span style="color: #000080;">;</span> count<span style="color: #000080;">&#41;</span> <span style="color: #c6c;">0</span>
printf <span style="color: #008080;">&quot;There are %d even numbers&quot;</span> count</pre></div></div>

<p>I guess the comparison isn&#8217;t really a fair one. The fundamental difference between C++ and F# lambdas is that they&#8217;re an afterthought in C++. In F# they&#8217;re a core, fundamental part of the language, and have been from day one. Functions are created, passed and bound as a matter of course.</p>
<p>The C++ heritage becomes obvious when you look at the finer points of its lambda syntax. For instance, having to specify whether to capture variables by reference or by value, in the &#8220;capture clause&#8221; or lambda-introducer. This is the type of distinction that both .NET programmers and functional programmers are not used to having to make.</p>
<h2>Other nice F# features</h2>
<p>Although not directly related to lambdas, there are some other F# language features that help make code more concise and understandable:</p>
<ol>
<li>
<h3>Sequence expressions</h3>
<p>F# has an extremely terse syntax for generating and manipulating sequences &#8211; collections that implement IEnumerable. This means you can easily generate collections and iterate over them, without the potential for off-by-one errors, the scourge of <code>for</code loops.
</li>
<li>
<h3>Fewer brackets</h3>
<p>In F#, whitespace is significant. It takes some time to get used to, but it ultimately results in cleaner code. It's been interesting to see the use of <code>#light</code> gradually become more and more standard as F# has neared an official release. Now it's implicit in all code. Try it, you'll like it.
</li>
<li>
<h3>Type-safe printf</h3>
<p>For some reason I always preferred the C style <code>printf</code> string formatting to C++s <code>cout</code> stream based version. There's something more readable about printf, but it suffers from a terrible lack of compile time type safety. This can be disastrous if, for instance, you happen to wrongly type the insert in an error message or other code path that's rarely hit. The one time you need it, the error handling itself generates an error! Ouch.</p>
<p><a href="http://72.47.193.211/wp-content/uploads/2009/10/printf_tooltip.png"><img src="http://www.voyce.com/wp-content/uploads/2009/10/printf_tooltip-150x64.png" alt="printf_tooltip" title="printf_tooltip" width="150" height="64" class="alignleft size-thumbnail wp-image-474" /></a><br />
Luckily, F# combines the best of both worlds with a compile-time type-safe printf! At first glance this can seem like some kind of magic to C++ developers (well, it did for me).
</li>
</ol>
<p>Now that F# is officially "out there" and available as a first class citizen in Visual Studio 2010, you should really take a look. I'm increasingly convinced that the cost of using C++, not necessarily the <a href="http://www.rachelslabnotes.com/2009/10/the-hidden-cost-of-c/">raw, low-level cost</a>, but the business costs involved with writing performant, maintainable, manageable code in C++, is getting too much to bear. But that's probably the basis for another post.</p>
<div><table border=0 bgcolor=#ffffff> <td><iframe src='http://digg.com/api/diggthis.php?w=new&amp;u=http%3A%2F%2Fwww.voyce.com%2Findex.php%2F2009%2F10%2F23%2Fcomparing-lambdas-in-c-and-f%2F&amp;t=Comparing+lambdas+in+C%2B%2B+and+F%23&amp;s=normal' height='80' width='52' frameborder='0' scrolling='no'></iframe></td></table></div><!-- Generated by Digg Digg plugin, 
    Author : Yong Mook Kim
    Website : http://www.mkyong.com/blog/digg-digg-wordpress-plugin/
	-->]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2009/10/23/comparing-lambdas-in-c-and-f/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
