<?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>Mon, 15 Mar 2010 08:42:49 +0000</lastBuildDate>
	
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>iPad &#8211; The rise of the naturalistic user interface</title>
		<link>http://www.voyce.com/index.php/2010/03/11/ipad-the-rise-of-the-naturalistic-user-interface/</link>
		<comments>http://www.voyce.com/index.php/2010/03/11/ipad-the-rise-of-the-naturalistic-user-interface/#comments</comments>
		<pubDate>Thu, 11 Mar 2010 01:05:53 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Usability]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[iPad]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=679</guid>
		<description><![CDATA[Apple's iPad applications make use of real-world objects in their user interfaces: books, newspapers, address books. What is it about the iPad that makes it a good platform for this kind of UI?]]></description>
			<content:encoded><![CDATA[<p>It was fascinating to see Apple unveiling its new iPad hardware recently, and one of the things that caught my eye were the interfaces of the various apps that were demonstrated. They look different from apps on other platforms, and even from the equivalent apps on the iPhone. It seems to me as if there&#8217;s been a change to a more naturalistic style of user interfaces. Why is this, and what is it about the iPad that makes it suited to this kind of UI?<br />
<span id="more-679"></span></p>
<h2>Form factor</h2>
<p>The most obvious reason that this kind of interface works on the iPad is the form factor of the device itself. Think about it: an iPhone is a small (well, smallish) object which has no physical, real-world equivalent. It&#8217;s not supposed to &#8220;be&#8221; anything other than a phone. The iPad, on the other hand, is intended to mimic an actual object, or rather, a variety of objects: a book, a newspaper or an address book for example. The interface for each of these uses reflects this directly: the address book looks like a &#8220;little black book&#8221;, complete with tabs. </p>
<p>The iPhone uses some of the same metaphors &#8211; like the address book for contacts &#8211; but the representation is abstract, whereas the iPad UI is literal, using an actual image of a book. The abstraction is necessary on the iPhone in order for it to remain usable with a smaller screen. Compare the iPad and iPhone Contacts interfaces:</p>
<table>
<tr>
<td><div id="attachment_682" class="wp-caption alignnone" style="width: 310px"><a href="http://www.voyce.com/wp-content/uploads/2010/02/contacts_ipad_fullpage_small.png"><img src="http://www.voyce.com/wp-content/uploads/2010/02/contacts_ipad_fullpage_small-300x230.png" alt="The realistic looking address book application on the iPad" title="contacts_ipad_fullpage_small" width="300" height="230" class="size-medium wp-image-682" /></a><p class="wp-caption-text">The realistic looking address book application on the iPad</p></div>
</td>
<td><div id="attachment_684" class="wp-caption alignnone" style="width: 130px"><a href="http://www.voyce.com/wp-content/uploads/2010/02/contacts_iphone_small.png"><img src="http://www.voyce.com/wp-content/uploads/2010/02/contacts_iphone_small-156x300.png" alt="iPhone contacts interface" title="contacts_iphone_small" width="120" height="230" class="size-medium wp-image-684" /></a><p class="wp-caption-text">iPhone contacts interface</p></div></td>
</tr>
</table>
<p>The abstract to realistic continuum has been explored extensively in the world of icons (explained brilliantly <a href="http://ignorethecode.net/blog/2010/01/21/realism_in_ui_design/">here</a>), but less so in the interface as a whole. Obviously some apps don&#8217;t have any form of real world equivalent (think System Preferences.app), so they&#8217;re likely to stay in a more abstract form. </p>
<h2>Display fidelity</h2>
<p>Of course, it&#8217;s always been possible to <i>represent</i> real objects on the screen, but without a display capable of a decent resolution it probably won&#8217;t look real. So another enabler for naturalistic UI is display technology: the more pixels and colour depth the better when it comes to rendering physical things. Realism often relies on subtle lighting and rich textures to achieve the desired effect. Anyone who&#8217;s ever attempted to render wood grain using 8-bit colour will appreciate how much easier it is with a 32-bit 1024&#215;768 display. </p>
<p>The need for display quality goes hand-in-hand with a need for more processing power to push the pixels. If the processing &#8220;oomph&#8221; required to render your interface with sufficient quality means that it&#8217;s not responsive enough, then you&#8217;ve failed by any measure. The iPad seems to have reached a sweet spot where display capabilities, raw power and form-factor meet to make naturalistic UIs a feasible approach.   </p>
<h2>Direct manipulation</h2>
<p><a href="http://www.voyce.com/wp-content/uploads/2010/03/Apple_Mouse_no.png"><img src="http://www.voyce.com/wp-content/uploads/2010/03/Apple_Mouse_no.png" alt="Apple_Mouse_no" title="Apple_Mouse_no" width="160" height="160" class="alignleft size-full wp-image-722" /></a>Up until the relatively recent introduction of direct manipulation technologies like touch-senstive displays, there&#8217;s a been a forced physical separation between users and their computer in the form of a mouse and keyboard. A drag operation using a mouse involves disconnected, abstract operations like pointing and clicking, which bear no relation to the object being acted upon. As such, there&#8217;s little use in having an extremely realistic representation of something to interact with, because the suspension-of-disbelief has already been broken. </p>
<p>But in the world of touch-based devices, our interactions are much closer to the physical actions we&#8217;d make, so having a closer visual representation to go along with it is beneficial. For instance, turning a page in an eBook and actually seeing the page flick over seems consistent when using a natural gesture like flicking a finger across the screen. Otherwise if you had to click a corner of the page and drag it across in a poor imitation of the physical action the visual aspects can quickly start to feel superfluous.   </p>
<p>Perhaps given the iPad&#8217;s larger interaction surface we can expect to see a wider and more expressive range of gestures supported?  </p>
<h2>History</h2>
<p>Of course, naturalistic UI isn&#8217;t really a new thing. It&#8217;s in use in quite a few applications already, albeit mostly in desktop apps, where capable hardware is more readily available. In fact, there was much a-twittering (not <i>all</i> of it from Will Shipley) about the similarity between the demo&#8217;d iPad apps and the interface of the fantastic Mac application <a href="http://delicious-monster.com/">Delicious Library</a>. I&#8217;m sure of course &#8211; how do they say it in the movie credits &#8211; the similarity is entirely coincidental&#8230;</p>
<table>
<tr>
<td valign="top"><div id="attachment_733" class="wp-caption alignnone" style="width: 303px"><img src="http://www.voyce.com/wp-content/uploads/2010/03/delicious_library_shrunk.png" alt="Delicious Library UI" title="delicious_library_shrunk" width="293" height="196" class="size-full wp-image-733" /><p class="wp-caption-text">Delicious Library UI</p></div></td>
<td><div id="attachment_734" class="wp-caption alignnone" style="width: 160px"><img src="http://www.voyce.com/wp-content/uploads/2010/03/ibooks_shrunk.png" alt="iBooks UI" title="ibooks_shrunk" width="150" height="199" class="size-full wp-image-734" /><p class="wp-caption-text">iBooks UI</p></div></td>
</tr>
</table>
<p><a href="http://www.voyce.com/wp-content/uploads/2010/03/rebirth_knobs_crop.png"><img src="http://www.voyce.com/wp-content/uploads/2010/03/rebirth_knobs_crop.png" alt="rebirth_knobs_crop" title="rebirth_knobs_crop" width="250" height="110" class="alignleft size-full wp-image-717" /></a>One of the first widespread uses of naturalistic UI elements was in software synths. Guys like <a href="http://www.propellerheads.se/">Propellerheads</a> and <a href="http://www.native-instruments.com/">Native Instruments</a> set about creating exact software duplicates of well-known and well-loved bits of <a href="http://en.wikipedia.org/wiki/Roland_TB-303">mid-80&#8217;s audio hardware</a>. The UIs included virtual versions of a huge number of physical elements that had never been used before: including things like sliders, LEDs, toggle buttons, rotary knobs and rocker switches. These interface elements were probably first seen in software-based mixing desks, but the techniques used to make them feel real have gone on to be used in many different ways. Even the lowly push button in both Windows and MacOS got an upgrade by application of some of the 3D effects that they originated. </p>
<h2>Where Now?</h2>
<p>It will be interesting to see what other types of app are given the iPad realism makeover. It certainly looks like all of the standard Apple apps are being changed, including Notes, iCal, iBooks and Contacts, which were shown in the launch presentation, but how will 3rd-party developers manage? It undoubtedly takes extra effort to make something look convincing when it can be compared to the physical object itself. </p>
<p>Apple has previously managed to get a good level of consistency in its abstract UIs by providing the various interface elements ready-made, but will that approach scale to this kind of UI? No doubt the developers who take great pride in the interfaces now will continue to strive to create apps that sit comfortably alongside Apple&#8217;s own, but perhaps there&#8217;ll just be a more obvious visual distinction between those guys and the less polished application user interfaces than there has been in the past.</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%2F11%2Fipad-the-rise-of-the-naturalistic-user-interface%2F&amp;t=iPad+-+The+rise+of+the+naturalistic+user+interface&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/11/ipad-the-rise-of-the-naturalistic-user-interface/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<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>
	</channel>
</rss>
