<?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>Not Rocket Science &#187; Development</title>
	<atom:link href="http://www.stum.de/category/development/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.stum.de</link>
	<description>Random thoughts of neat disorder</description>
	<lastBuildDate>Sun, 08 Aug 2010 00:16:47 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>The one dynamic language I think Microsoft needs to embrace in .net&#8230;</title>
		<link>http://www.stum.de/2010/08/08/the-one-dynamic-language-i-think-microsoft-needs-to-embrace-in-net/</link>
		<comments>http://www.stum.de/2010/08/08/the-one-dynamic-language-i-think-microsoft-needs-to-embrace-in-net/#comments</comments>
		<pubDate>Sun, 08 Aug 2010 00:16:47 +0000</pubDate>
		<dc:creator>mstum</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://www.stum.de/?p=890</guid>
		<description><![CDATA[So a few days ago, Jimmy Schementi announced the death of IronRuby. Oh, sorry, "IronRuby isn't dead, it's just back in the hands of the community" which is essentially the same. Now, while there may be a chance for IronRuby to survive, I personally think it's not something that Microsoft should do, so I think [...]]]></description>
			<content:encoded><![CDATA[<p>So a few days ago, Jimmy Schementi announced the <a href="http://blog.jimmy.schementi.com/2010/08/start-spreading-news-future-of-jimmy.html">death of IronRuby</a>. Oh, sorry, "<a href="http://twitter.com/jschementi/status/20508631769">IronRuby isn't dead, it's just back in the hands of the community</a>" which is essentially <a href="http://evain.net/blog/articles/2010/08/07/on-ironruby">the same</a>.</p>
<p>Now, while there may be a chance for IronRuby to survive, I personally think it's not something that Microsoft should do, so I think it makes sense for them to kill it off internally. Same for IronPython. I think the DLR is a great addition to .net though, and I think there is a far better language already available.</p>
<p><a href="http://en.wikipedia.org/wiki/JavaScript">JavaScript</a>.</p>
<p>Many of us perceive JavaScript as a Browser-only language that is hampered by different implementations in different Browsers (<a href="http://blog.coderlab.us/2006/04/18/the-textcontent-and-innertext-properties/">textContent vs. innerText</a> anyone?), something which is being addressed through the use of frameworks like <a href="http://jquery.com/">jQuery</a>.</p>
<p>But think it one step further: How many languages do you need to write a Web Application? At least two: JavaScript and whatever backend language you use, for example C#, Java, Ruby or PHP. How do you write Form Validation? You write separate Code for the Client Side and for the Server Side so that users get instant feedback without being able to compromise the system by turning JavaScript off. This is stupid and a severe violation of <a href="http://en.wikipedia.org/wiki/DRY">DRY</a>. Also there are subtle differences between the Code, for example because JavaScript's RegEx Engine works slightly different than the .net one.</p>
<p>.net is at it's core a language-independent technology that doesn't only support but encourage using multiple languages. Sure, there are only 3-4 really supported languages which are rarely mixed (Some people mix C++/CLI with C# or VB.net for some COM stuff, or F# with C# for financial/statistic stuff) and some languages that have some limited support (<a href="http://en.wikipedia.org/wiki/Boo_(programming_language)">Boo</a> is my favorite in this category).</p>
<p>So why not do what's logical and embrace JavaScript as a Server-Side technology? <a href="http://nodejs.org/">Node.js</a> arrived recently and showed it's possible. Microsoft already somewhat supports JavaScript in Visual Studio (although the experience is far less than stellar) and they even had their own bastard child in form of <a href="http://en.wikipedia.org/wiki/JScript.NET">JScript.net</a>.</p>
<p>There is a big discussion whether or not C# is a good language to write Web Applications in. People point at <a href="http://cukes.info/">Cucumber</a> and talk about how great Ruby works with the Web while C# feels like a chore because of it's static typing, verbose Syntax and need for IoC Containers to do Unit Testing properly. Other people point at the insecurity of dynamic languages, about the lack of compiler errors, about the confusion created by not having to declare variables which leads to subtle bugs like `$total = 0; foreach(item in items) $totel += item.price`.</p>
<p>I say: Use both. Use C# for your backend code, for your Business Classes. Get Compiler Errors when you screw up. Make sure everything needs to be explicitly casted to whatever it has to be and that all variables have to be defined officially before use. For the frontend, use JavaScript. Create your Views and View Models like you would create them in the browser, through DOM Manipulation. Write and maintain your verification code exactly once, in one language, browser and server side. Feel free to whatever crazy manipulation you need to do without having to declare and cast tons of variables. If you screw up, it's "only" your Views, not your data structure because that's C# code.</p>
<p>Utopia? Maybe. JavaScript is not without it's faults and it may not be as elegant as Ruby in places. People would have to learn two languages, and people may ask "Why should we switch to an insecure language if C# served us well for years?" - well, the latter people are usually the ones who don't think they need Unit Testing and believe that WebForms is a perfectly good technology, so let them continue to use it and let the rest of us move forward to face the challenges of 2010 and beyond.</p>
<p>Customers want better apps. They want AJAX, they want snappy, cool looking UI. The Browser market is not a "Make sure it runs in IE and doesn't suck in Netscape 4.78" market anymore. We need to create cool apps, and we need to run them on Internet Explorer, Firefox, Safari on OS X, Safari on iPhone and Android. Our Web Apps need to do more in less time.</p>
<p>And Microsoft is in a great position because they have the foundation already built. Make Visual Studio a kick-ass JavaScript Development tool and bring it to the server side. Give us great debugging because even with FireBug and the IE Development Tools, it still sucks. Look what Node.js did. Look what you are doing with <a href="http://blogs.msdn.com/b/ie/archive/2010/03/18/the-new-javascript-engine-in-internet-explorer-9.aspx">Internet Explorer 9's JS Engine</a>. Look what you have with <a href="http://en.wikipedia.org/wiki/Active_Scripting">Active Scripting</a> and look what you did with <a href="http://en.wikipedia.org/wiki/JScript.NET">JScript.net</a>.</p>
<p>It's incredible to see that Microsoft has all this technology already lying around and that no one had the idea to just combine them all together for ASP.net. Sure, Internet Explorer got a lot of (well deserved) crap for issues in it's JavaScript implementation, but IE9's previews look really promising.</p>
<p>Because let's face it: Any .net Language not supported by Microsoft in Visual Studio is doomed.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stum.de/2010/08/08/the-one-dynamic-language-i-think-microsoft-needs-to-embrace-in-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>64-Bit Bitfield Cheat Sheet</title>
		<link>http://www.stum.de/2010/08/02/64-bit-bitfield-cheat-sheet/</link>
		<comments>http://www.stum.de/2010/08/02/64-bit-bitfield-cheat-sheet/#comments</comments>
		<pubDate>Mon, 02 Aug 2010 10:43:58 +0000</pubDate>
		<dc:creator>mstum</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://www.stum.de/?p=884</guid>
		<description><![CDATA[Just as a cheat sheet for me, a 64-Bit Bitfield in Dec and Hex. Bit Int Hex 1 1 0x1 2 2 0x2 3 4 0x4 4 8 0x8 5 16 0x10 6 32 0x20 7 64 0x40 8 128 0x80 9 256 0x100 10 512 0x200 11 1024 0x400 12 2048 0x800 13 4096 [...]]]></description>
			<content:encoded><![CDATA[<p>Just as a cheat sheet for me, a 64-Bit Bitfield in Dec and Hex.</p>
<table cellspacing="0" cellpadding="0" width="600">
<tbody>
<tr>
<td width="30" valign="top"><strong>Bit</strong></td>
<td width="285" valign="top"><strong>Int</strong></td>
<td width="285" valign="top"><strong>Hex</strong></td>
</tr>
<tr>
<td valign="top"><strong>1</strong></td>
<td valign="top">1</td>
<td valign="top">0x1</td>
</tr>
<tr>
<td valign="top"><strong>2</strong></td>
<td valign="top">2</td>
<td valign="top">0x2</td>
</tr>
<tr>
<td valign="top"><strong>3</strong></td>
<td valign="top">4</td>
<td valign="top">0x4</td>
</tr>
<tr>
<td valign="top"><strong>4</strong></td>
<td valign="top">8</td>
<td valign="top">0x8</td>
</tr>
<tr>
<td valign="top"><strong>5</strong></td>
<td valign="top">16</td>
<td valign="top">0x10</td>
</tr>
<tr>
<td valign="top"><strong>6</strong></td>
<td valign="top">32</td>
<td valign="top">0x20</td>
</tr>
<tr>
<td valign="top"><strong>7</strong></td>
<td valign="top">64</td>
<td valign="top">0x40</td>
</tr>
<tr>
<td valign="top"><strong>8</strong></td>
<td valign="top">128</td>
<td valign="top">0x80</td>
</tr>
<tr>
<td valign="top"><strong>9</strong></td>
<td valign="top">256</td>
<td valign="top">0x100</td>
</tr>
<tr>
<td valign="top"><strong>10</strong></td>
<td valign="top">512</td>
<td valign="top">0x200</td>
</tr>
<tr>
<td valign="top"><strong>11</strong></td>
<td valign="top">1024</td>
<td valign="top">0x400</td>
</tr>
<tr>
<td valign="top"><strong>12</strong></td>
<td valign="top">2048</td>
<td valign="top">0x800</td>
</tr>
<tr>
<td valign="top"><strong>13</strong></td>
<td valign="top">4096</td>
<td valign="top">0x1000</td>
</tr>
<tr>
<td valign="top"><strong>14</strong></td>
<td valign="top">8192</td>
<td valign="top">0x2000</td>
</tr>
<tr>
<td valign="top"><strong>15</strong></td>
<td valign="top">16384</td>
<td valign="top">0x4000</td>
</tr>
<tr>
<td valign="top"><strong>16</strong></td>
<td valign="top">32768</td>
<td valign="top">0x8000</td>
</tr>
<tr>
<td valign="top"><strong>17</strong></td>
<td valign="top">65536</td>
<td valign="top">0x10000</td>
</tr>
<tr>
<td valign="top"><strong>18</strong></td>
<td valign="top">131072</td>
<td valign="top">0x20000</td>
</tr>
<tr>
<td valign="top"><strong>19</strong></td>
<td valign="top">262144</td>
<td valign="top">0x40000</td>
</tr>
<tr>
<td valign="top"><strong>20</strong></td>
<td valign="top">524288</td>
<td valign="top">0x80000</td>
</tr>
<tr>
<td valign="top"><strong>21</strong></td>
<td valign="top">1048576</td>
<td valign="top">0x100000</td>
</tr>
<tr>
<td valign="top"><strong>22</strong></td>
<td valign="top">2097152</td>
<td valign="top">0x200000</td>
</tr>
<tr>
<td valign="top"><strong>23</strong></td>
<td valign="top">4194304</td>
<td valign="top">0x400000</td>
</tr>
<tr>
<td valign="top"><strong>24</strong></td>
<td valign="top">8388608</td>
<td valign="top">0x800000</td>
</tr>
<tr>
<td valign="top"><strong>25</strong></td>
<td valign="top">16777216</td>
<td valign="top">0x1000000</td>
</tr>
<tr>
<td valign="top"><strong>26</strong></td>
<td valign="top">33554432</td>
<td valign="top">0x2000000</td>
</tr>
<tr>
<td valign="top"><strong>27</strong></td>
<td valign="top">67108864</td>
<td valign="top">0x4000000</td>
</tr>
<tr>
<td valign="top"><strong>28</strong></td>
<td valign="top">134217728</td>
<td valign="top">0x8000000</td>
</tr>
<tr>
<td valign="top"><strong>29</strong></td>
<td valign="top">268435456</td>
<td valign="top">0x10000000</td>
</tr>
<tr>
<td valign="top"><strong>30</strong></td>
<td valign="top">536870912</td>
<td valign="top">0x20000000</td>
</tr>
<tr>
<td valign="top"><strong>31</strong></td>
<td valign="top">1073741824</td>
<td valign="top">0x40000000</td>
</tr>
<tr>
<td valign="top"><strong>32</strong></td>
<td valign="top">2147483648</td>
<td valign="top">0x80000000</td>
</tr>
<tr>
<td valign="top"><strong>33</strong></td>
<td valign="top">4294967296</td>
<td valign="top">0x100000000</td>
</tr>
<tr>
<td valign="top"><strong>34</strong></td>
<td valign="top">8589934592</td>
<td valign="top">0x200000000</td>
</tr>
<tr>
<td valign="top"><strong>35</strong></td>
<td valign="top">17179869184</td>
<td valign="top">0x400000000</td>
</tr>
<tr>
<td valign="top"><strong>36</strong></td>
<td valign="top">34359738368</td>
<td valign="top">0x800000000</td>
</tr>
<tr>
<td valign="top"><strong>37</strong></td>
<td valign="top">68719476736</td>
<td valign="top">0x1000000000</td>
</tr>
<tr>
<td valign="top"><strong>38</strong></td>
<td valign="top">137438953472</td>
<td valign="top">0x2000000000</td>
</tr>
<tr>
<td valign="top"><strong>39</strong></td>
<td valign="top">274877906944</td>
<td valign="top">0x4000000000</td>
</tr>
<tr>
<td valign="top"><strong>40</strong></td>
<td valign="top">549755813888</td>
<td valign="top">0x8000000000</td>
</tr>
<tr>
<td valign="top"><strong>41</strong></td>
<td valign="top">1099511627776</td>
<td valign="top">0x10000000000</td>
</tr>
<tr>
<td valign="top"><strong>42</strong></td>
<td valign="top">2199023255552</td>
<td valign="top">0x20000000000</td>
</tr>
<tr>
<td valign="top"><strong>43</strong></td>
<td valign="top">4398046511104</td>
<td valign="top">0x40000000000</td>
</tr>
<tr>
<td valign="top"><strong>44</strong></td>
<td valign="top">8796093022208</td>
<td valign="top">0x80000000000</td>
</tr>
<tr>
<td valign="top"><strong>45</strong></td>
<td valign="top">17592186044416</td>
<td valign="top">0x100000000000</td>
</tr>
<tr>
<td valign="top"><strong>46</strong></td>
<td valign="top">35184372088832</td>
<td valign="top">0x200000000000</td>
</tr>
<tr>
<td valign="top"><strong>47</strong></td>
<td valign="top">70368744177664</td>
<td valign="top">0x400000000000</td>
</tr>
<tr>
<td valign="top"><strong>48</strong></td>
<td valign="top">140737488355328</td>
<td valign="top">0x800000000000</td>
</tr>
<tr>
<td valign="top"><strong>49</strong></td>
<td valign="top">281474976710656</td>
<td valign="top">0x1000000000000</td>
</tr>
<tr>
<td valign="top"><strong>50</strong></td>
<td valign="top">562949953421312</td>
<td valign="top">0x2000000000000</td>
</tr>
<tr>
<td valign="top"><strong>51</strong></td>
<td valign="top">1125899906842624</td>
<td valign="top">0x4000000000000</td>
</tr>
<tr>
<td valign="top"><strong>52</strong></td>
<td valign="top">2251799813685248</td>
<td valign="top">0x8000000000000</td>
</tr>
<tr>
<td valign="top"><strong>53</strong></td>
<td valign="top">4503599627370496</td>
<td valign="top">0x10000000000000</td>
</tr>
<tr>
<td valign="top"><strong>54</strong></td>
<td valign="top">9007199254740992</td>
<td valign="top">0x20000000000000</td>
</tr>
<tr>
<td valign="top"><strong>55</strong></td>
<td valign="top">18014398509481984</td>
<td valign="top">0x40000000000000</td>
</tr>
<tr>
<td valign="top"><strong>56</strong></td>
<td valign="top">36028797018963968</td>
<td valign="top">0x80000000000000</td>
</tr>
<tr>
<td valign="top"><strong>57</strong></td>
<td valign="top">72057594037927936</td>
<td valign="top">0x100000000000000</td>
</tr>
<tr>
<td valign="top"><strong>58</strong></td>
<td valign="top">144115188075855872</td>
<td valign="top">0x200000000000000</td>
</tr>
<tr>
<td valign="top"><strong>59</strong></td>
<td valign="top">288230376151711744</td>
<td valign="top">0x400000000000000</td>
</tr>
<tr>
<td valign="top"><strong>60</strong></td>
<td valign="top">576460752303423488</td>
<td valign="top">0x800000000000000</td>
</tr>
<tr>
<td valign="top"><strong>61</strong></td>
<td valign="top">1152921504606846976</td>
<td valign="top">0x1000000000000000</td>
</tr>
<tr>
<td valign="top"><strong>62</strong></td>
<td valign="top">2305843009213693952</td>
<td valign="top">0x2000000000000000</td>
</tr>
<tr>
<td valign="top"><strong>63</strong></td>
<td valign="top">4611686018427387904</td>
<td valign="top">0x4000000000000000</td>
</tr>
<tr>
<td valign="top"><strong>64</strong></td>
<td valign="top">9223372036854775808</td>
<td valign="top">0x8000000000000000</td>
</tr>
</tbody>
</table>
<p>Checking if a bit is set:</p>
<pre class="prettyprint lang-cs">
// AND: Only return 1 if both bits are 1
// 0011 &#038; 0100 = 0000
// 0111 &#038; 0100 = 0100
isSet = (value &#038; 0x4) == 0x4;
isSet = (value &#038; 0x4) > 0;
</pre>
<p>Setting a bit:</p>
<pre class="prettyprint lang-cs">
// OR: If either operand is 1, return 1.
// 0011 | 0100 = 0111
newvalue = oldvalue | 0x4; // |=
</pre>
<p>Unsetting a bit:</p>
<pre class="prettyprint lang-cs">
// NOT: Invert the Bits
// ~0100 = 1011
// AND: Return 1 if both bits are 1
// 0011 &#038; 1011 = 0011
// 0111 &#038; 1011 = 0011
newvalue = oldvalue &#038; (~0x4) // &#038;= ~0x4;
</pre>
<p>Toggling a bit:</p>
<pre class="prettyprint lang-cs">
// XOR: If both bits are equal, return 0
// 0111 ^ 0100 = 0011
// 0011 ^ 0100 = 0111
newvalue = oldvalue ^ 0x4; // ^=
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.stum.de/2010/08/02/64-bit-bitfield-cheat-sheet/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Careful with SPContext.Current&#8230;</title>
		<link>http://www.stum.de/2010/06/12/careful-with-spcontext-current/</link>
		<comments>http://www.stum.de/2010/06/12/careful-with-spcontext-current/#comments</comments>
		<pubDate>Sat, 12 Jun 2010 22:33:05 +0000</pubDate>
		<dc:creator>mstum</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Sharepoint]]></category>

		<guid isPermaLink="false">http://www.stum.de/?p=863</guid>
		<description><![CDATA[...as it will be NULL within a Timer Job or Workflow. I have some shared Data Access classes that use SPContext.Current.Web all over the place and now that I want to use them from within a Timer Job, I have to refactor them to take a SPWeb as a Parameter...]]></description>
			<content:encoded><![CDATA[<p>...as it will be NULL within a Timer Job or Workflow. I have some shared Data Access classes that use SPContext.Current.Web all over the place and now that I want to use them from within a Timer Job, I have to refactor them to take a SPWeb as a Parameter...</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stum.de/2010/06/12/careful-with-spcontext-current/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Why doesn&#8217;t Windows offer a working help system anymore?</title>
		<link>http://www.stum.de/2010/06/11/why-doesnt-windows-offer-a-working-help-system-anymore/</link>
		<comments>http://www.stum.de/2010/06/11/why-doesnt-windows-offer-a-working-help-system-anymore/#comments</comments>
		<pubDate>Fri, 11 Jun 2010 05:32:39 +0000</pubDate>
		<dc:creator>mstum</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://www.stum.de/?p=857</guid>
		<description><![CDATA[If you are developing Windows Desktop applications, you may want to offer context-sensitive help, triggered either by pressing F1 or by clicking on the question mark icon in the title bar and on an element. Back in the old days (starting in 1990 and de-facto ending in 2006), there was WinHelp. Now, WinHelp wasn't exactly [...]]]></description>
			<content:encoded><![CDATA[<p>If you are developing Windows Desktop applications, you may want to offer context-sensitive help, triggered either by pressing F1 or by clicking on the question mark icon in the title bar and on an element. Back in the old days (starting in 1990 and de-facto ending in 2006), there was <a href="http://en.wikipedia.org/wiki/WinHelp">WinHelp</a>.<br />
<img src="http://www.stum.de/wp-content/uploads/2010/06/winhelp2k.gif" alt="" title="winhelp2k" width="621" height="470" class="aligncenter size-full wp-image-859" /></p>
<p>Now, WinHelp wasn't exactly beautiful and in recent years (after 1996 that is), the "Maximize Database Size" dialog was <a href="http://www.joelonsoftware.com/uibook/chapters/fog0000000059.html">downright stupid</a>, but WinHelp had all the features a Help system needs: Articles are organized in Chapters and can contain Images, Links and basic formatting. And it allowed your application to open a specific page, providing contextual help.</p>
<p>But most importantly, WinHelp just WORKS. Really, you press F1 and maybe you have to "Maximize Database Size" once, but then it opens. I never ever had a problem with WinHelp.</p>
<p>But Microsoft decided it wasn't modern anymore. That we needed something new. Granted, WinHelp clearly showed it's age, and creation of Help Files was somewhat complicated. So they introduced <a href="http://en.wikipedia.org/wiki/Microsoft_Compiled_HTML_Help">Compiled HTML Help</a>, or CHM. It is a modern Help system, allowing you much more freedom with your layout and styling. It's a really good format, with one tiny little problem: <strong>CHM doesn't actually work</strong>:<br />
<img src="http://www.stum.de/wp-content/uploads/2010/06/CHMFail.png" alt="" title="CHMFail" width="600" height="450" class="aligncenter size-full wp-image-858" /></p>
<p>Turns out that CHM is displayed through the MSHTML Control (which is essentially an embedded Internet Explorer) and thus it has some security limitations. The most important one is that CHM files on non-trusted (e.g., network) locations simply don't work.</p>
<p>Now, you may say that this can be resolved. The file can be unblocked, or the path can be set to trusted. An Application Installer could do that. I reply: Doesn't matter. It's a Help system. It has to work without configuration. Press F1, get help. If I'm in a situation I need help using my application and my help system tells me that it wants some treats first, it's a failure. Besides, not every Application has an installer because not every application needs one. A large amount of applications are just DLLs (like the one the above screenshot is from) or ZIPped application files.</p>
<p>So CHM is a complete and utter failure, and Microsoft at least acknowledged that by killing off Microsoft Help 2 and starting a new approach with <a href="http://en.wikipedia.org/wiki/Microsoft_Assistance_Markup_Language">MAML</a>. However, MAML is not a Help System, it's a language that can be used as source to be converted into an output format like HTML, RTF or whatever. In other words, Microsoft has created <a href="http://en.wikipedia.org/wiki/DocBook">DocBook</a> again without actually solving the problem of displaying help.</p>
<p>The real successor to CHM seems to be the HelpPane introduced in Windows Vista and included in Windows 2008 and 7 as well. Those help files have the extension h1s and a nice little icon, so Windows knows what they are. There is our new Help system, right? Well, try to double click one of those h1s files...</p>
<p><img src="http://www.stum.de/wp-content/uploads/2010/06/h1s.png" alt="" title="h1s" width="429" height="192" class="aligncenter size-full wp-image-861" /></p>
<p>Hmmm... So Microsoft didn't just register a file type handler for h1s files. Well, <a href="http://www.help-info.de/en/Help_Info_AP_Help/ap_help_GuidedHelp.htm">can't be that hard to do, can it</a>?</p>
<blockquote><p>AP Help - Guided Help - Technical FAQ</p>
<p>Can I launch Guided Help through other means besides the Help Pane?<br />
Yes, but you must create and publish the Guided Help topic through Help. Once you have a Guided Help topic compiled into an H1S file and installed (at this stage only possible for Microsoft and OEM's), you can launch it directly through a command line if you wish.<br />
The syntax is:</p>
<p>%systemroot%\system32\acw.exe –Extensions GuidedHelp.dll –taskID mshelp://windows/?id=id-of-your-help-topic –ExecutionMode DoIt | ShowMe</p>
<p>For a fast impression copy following text to your run dialog:</p>
<p>%SystemRoot%\System32\ACW.exe -Extensions GuidedHelp.dll -taskID mshelp://windows/?id=3726934c-1315-4c29-bd4d-e42c10225e5a -ExecutionMode ShowMe</p></blockquote>
<p>Excuse me, but ARE YOU FRIGGIN' KIDDING ME? Oh, yes you are, let me just <a href="http://msdn.microsoft.com/en-us/library/bb757030.aspx">quote Microsoft</a>:</p>
<blockquote><p>Microsoft is committed to providing Help and Support technology in the Windows® platform and will continue to investigate new solutions for software developers.</p></blockquote>
<p>Sorry, but if "comitted" means "Killing off perfectly working solutions and replacing them with a plethora of broken solutions every two years" then you are absolutely right, because that's what you are doing. WinHelp survived 16 Years and if you would still ship it with Vista and 7 then it would still be alive.  So you as an application developer, what can you do? WinHelp isn't part of Vista and Windows 7 anymore and you're not allowed to distribute it with your application. CHM/H1S doesn't work. What are your alternatives?</p>
<p>Some applications use PDF. They offer rich layout and a Table of Content, however there is no standard reader. Sure, there is Adobe Reader, but you can't easily control it (e.g., open a PDF on a given page) - if the user has a version that is too old or too new for your application, you may run into issues. And if the user doesn't have Adobe Reader (or any other PDF reader) installed, you have to explain why someone would download an additional program just because you're not competent enough to include help. So PDF is not an option.</p>
<p>What about HTML Files? Everyone has a browser, even the short lived Windows 7 E Editions included MSHTML allowing you to at least display HTML within an application. The major downside of HTML is that you can't control which browser displays it, so you have to stay conservative and make sure old Internet Explorer or Firefox browsers display it (say goodbye to transparent PNGs...). JavaScript maybe tricky (also due to widely spread Extensions like NoScript). And instead of one help file, you have a whole folder. Adding contextual help to your application is somewhat possible, but overall you simply lose the ability to control and test how the help looks and works.</p>
<p>This is possibly the moment where you expect me to say "But after researching all these non-working options, here is the one that works!". Sorry, can't do that. I don't know a single Help system that works on Windows Vista/7/2008. I <a href="http://stackoverflow.com/questions/1131/">asked on StackOverflow</a> a long time ago and the consensus was the same.</p>
<p>It's really sad that a task that seems so simple and straight forward is too hard for Microsoft. Seriously, all that you need to do is to take a simple container format, some basic formatting options, the ability to link and embed images and an API to call Help from your application. If you want, include video support with a standard codec (keeping in mind Windows N/KN Editions)</p>
<p>Simple, easy, straight-forward, hassle-free or in other words: Exactly how a Help System should work. Exactly how WinHelp worked since 1990 before it was brutally murdered. Rest in Piece WinHelp, we miss you dearly.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stum.de/2010/06/11/why-doesnt-windows-offer-a-working-help-system-anymore/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>A Visual Studio Macro to insert a new Guid</title>
		<link>http://www.stum.de/2010/04/29/a-visual-studio-macro-to-insert-a-new-guid/</link>
		<comments>http://www.stum.de/2010/04/29/a-visual-studio-macro-to-insert-a-new-guid/#comments</comments>
		<pubDate>Thu, 29 Apr 2010 11:24:36 +0000</pubDate>
		<dc:creator>mstum</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://www.stum.de/?p=851</guid>
		<description><![CDATA[I've been trying to create some SharePoint Content Types and List Definitions recently, and everyone who done that before knows what you need for that: Guids, and quite a few of them. One for each Field, Feature, Solution... So instead of using GuidGen, I wanted something that inserts a new Guid at the cursor position [...]]]></description>
			<content:encoded><![CDATA[<p>I've been trying to create some SharePoint Content Types and List Definitions recently, and everyone who done that before knows what you need for that: Guids, and quite a few of them. One for each Field, Feature, Solution... So instead of using GuidGen, I wanted something that inserts a new Guid at the cursor position in the Editor when I press a certain keyboard shortcut.</p>
<p>Luckily, this is rather easy with the Macro Editor. Just create a new Macro/Module and enter this code:</p>
<pre class="prettyprint">
Sub InsertGuid()
    Dim newId As String = Guid.NewGuid().ToString("B")
    Dim doc As Document = DTE.ActiveDocument
    Dim textDoc As TextDocument = CType(doc.Object("TextDocument"), TextDocument)
    textDoc.StartPoint.CreateEditPoint()
    textDoc.Selection.Insert(newId)
End Sub
</pre>
<p>You can then go to Tools / Options / Environment / Keyboard and look for the Macro you just created (Macros.MyMacros.SomeModule.InsertGuid) and assign a Keyboard shortcut to it.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stum.de/2010/04/29/a-visual-studio-macro-to-insert-a-new-guid/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Writing a BF Compiler for .net (Part 5: [ and ] &#8211; while loops in IL)</title>
		<link>http://www.stum.de/2010/04/28/writing-a-bf-compiler-for-net-part-5-and-while-loops-in-il/</link>
		<comments>http://www.stum.de/2010/04/28/writing-a-bf-compiler-for-net-part-5-and-while-loops-in-il/#comments</comments>
		<pubDate>Wed, 28 Apr 2010 06:02:53 +0000</pubDate>
		<dc:creator>mstum</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[brainfk]]></category>

		<guid isPermaLink="false">http://www.stum.de/?p=842</guid>
		<description><![CDATA[The final two commands we're looking at are [ and ]. Their description in the first article was a bit cryptic, [ was described as Go to the next instruction if the byte at the memory pointer is not 0, otherwise move it past the matching ] instruction while ] was described as Go to [...]]]></description>
			<content:encoded><![CDATA[<p>The final two commands we're looking at are [ and ]. Their description in the <a href="http://www.stum.de/2010/04/09/writing-a-bf-compiler-for-net-part-1-explanation-of-the-language-and-interpreter-in-c/">first article</a> was a bit cryptic, [ was described as</p>
<blockquote><p>
Go to the next instruction if the byte at the memory pointer is not 0, otherwise move it past the matching ] instruction
</p></blockquote>
<p>while ] was described as </p>
<blockquote><p>
Go to the instruction after the matching [ if the byte at the memory pointer is not 0, else move it past the ]
</p></blockquote>
<p>In C# code, this is a lot simpler:</p>
<pre class="prettyprint lang-cs">
// BF Code for this: [-]
while (memory[pointer] > 0)
{
    // Instructions between [ and ]
    // The following instruction is only to have a body
    memory[pointer]--;
}
</pre>
<p>It's a while-loop. It's important to note that we have to use a pre-test loop, that is a loop that checks the condition before executing the loop (as opposed to a do-while loop which executes the code block at least once and checks afterwards).</p>
<p>So how does a while loop look in .net IL?</p>
<pre class="prettyprint">
// See note below regarding .s suffix on br.s and bgt.s
IL_0000:  br.s       IL_001f
// This is the memory[pointer]-- instruction
IL_0002:  ldsfld     uint8[] BFHelloWorldCSharp.Program::memory
IL_0007:  ldsfld     int16 BFHelloWorldCSharp.Program::pointer
IL_000c:  ldelema    [mscorlib]System.Byte
IL_0011:  dup
IL_0012:  ldobj      [mscorlib]System.Byte
IL_0017:  ldc.i4.1
IL_0018:  sub
IL_0019:  conv.u1
IL_001a:  stobj      [mscorlib]System.Byte
// This is the while loop
IL_001f:  ldsfld     uint8[] BFHelloWorldCSharp.Program::memory
IL_0024:  ldsfld     int16 BFHelloWorldCSharp.Program::pointer
IL_0029:  ldelem.u1
IL_002a:  ldc.i4.0
IL_002b:  bgt.s      IL_0002
</pre>
<p><strong>GOTO considered harmful?</strong><br />
Okay, this looks complicated, but it is easy. To explain it, we have to open Pandora's Box and look at the dirtiest secret there is in development: At Machine Level, GOTOs are essential.<br />
Ha, take that <a href="http://userweb.cs.utexas.edu/users/EWD/ewd02xx/EWD215.PDF">Dijkstra</a>!</p>
<p>Regardless how much you abstract it away, control structures like while have to be translated as "GOTO's", or more precisely as jumps to addresses to continue execute code from. In .net, this is not called GOTO though, it's called Branch.</p>
<p>Our code has three parts: A single GOTO/Branch instruction at the beginning, the body of the loop (in our case the single memory[pointer]-- instruction) and then the while check.</p>
<p>So we start with <a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.br_s.aspx">br.s</a>, which is described as</p>
<blockquote><p>
Unconditionally transfers control to a target instruction (short form).
</p></blockquote>
<p>In other words, this is a GOTO and it goes to IL_001f. The code starting from here does the while-check: Load memory and pointer onto the stack. Then load the value of memory[pointer] onto the stack as Unsigned 8-Bit Int. Afterwards, push the number 0 to the stack.</p>
<p>Our evaluation stack now contains the value of memory[pointer] and the number 0. Then we have the new <a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.bgt_s.aspx">bgt.s command</a>:</p>
<blockquote><p>
Transfers control to a target instruction (short form) if the first value is greater than the second value.
</p></blockquote>
<p>In other words and Pseudocode: <code>if(memory[pointer] > 0) goto IL_0002;</code></p>
<p>The code starting from IL_0002 is our memory[pointer]-- instruction which will be executed and then we'll do the while-check again.</p>
<p>In Debug mode, the bgt instruction is not used. Instead, the check is done much more complicated. Feel free to look it up using ILDASM, but Debug Mode uses this C# Pseudocode to capture the result of the comparison into a local variable:</p>
<pre class="prettyprint">
bool DoJump = memory[pointer] > 0;
if(DoJump) goto IL_0002;
</pre>
<p>This is useful for Debugging (who would've thought it, given that it's a debug build?), but rather heavy compared to Release mode (8 instructions and a local variable compared to 5 instructions without).</p>
<p>Looking at that, you can easily imagine what the difference between a while and a <a href="http://msdn.microsoft.com/en-us/library/370s1zax.aspx">do while</a> loop is: The do while loop does not have the br.s instruction at the beginning. It therefore executes the method body at least once before it enters the while-check.</p>
<p>Before I end this post, I want to talk about short form commands.</p>
<p><strong>What is "Short Form"?</strong><br />
If you look at the IL Commands, some say "Short Form". What does this mean? Well, normally all addresses are 32 Bit, that is 4 Bytes. If you want an unconditional jump, you would use the <a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.br.aspx">br command</a> with the target address. However, this means you'll have 5 bytes in the target file - 1 for the Br Instruction and 4 for the target. As this instruction is so common, it would be a massive overhead to always have to write 5 bytes to the file.</p>
<p>Short Form commands only take 1 byte for the target address. The target here is described as</p>
<blockquote><p>
1-byte signed offset from the beginning of the instruction following the current instruction
</p></blockquote>
<p>So instead of giving an absolute address, we give a relative address to jump to instead. This only works if the target is less than ~125 bytes away (signed offset!) of course, so it's a lot less flexible and your compiler needs to know the distance between the target and the jump instructions. However, the savings are huge as short form only requires 2 bytes, less than half of the full instructions.</p>
<p>This concludes the command overview. Part 6 will finally show how we will write our compiler.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stum.de/2010/04/28/writing-a-bf-compiler-for-net-part-5-and-while-loops-in-il/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Writing a BF Compiler for .net (Part 4: . and ,)</title>
		<link>http://www.stum.de/2010/04/27/writing-a-bf-compiler-for-net-part-4-and/</link>
		<comments>http://www.stum.de/2010/04/27/writing-a-bf-compiler-for-net-part-4-and/#comments</comments>
		<pubDate>Tue, 27 Apr 2010 03:45:31 +0000</pubDate>
		<dc:creator>mstum</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[brainfk]]></category>

		<guid isPermaLink="false">http://www.stum.de/?p=835</guid>
		<description><![CDATA[In the last two parts we tackled 4 of the 8 possible BF Commands: &#62;, &#60;, +, -. Now we look at . and , for input and output. When working with a Console Application, it only makes sense to use the built-in commands Console.Write and Console.Read. Let's look at output (the . command) first. [...]]]></description>
			<content:encoded><![CDATA[<p>In the last <a href="http://www.stum.de/2010/04/12/writing-a-bf-compiler-for-net-part-2-writing-bf-in-c-and-looking-at-the-il/">two</a> <a href="http://www.stum.de/2010/04/19/writing-a-bf-compiler-for-net-part-3-pointer-and-pointer/">parts</a> we tackled 4 of the 8 possible BF Commands: &gt;, &lt;, +, -. Now we look at . and , for input and output.</p>
<p>When working with a Console Application, it only makes sense to use the built-in commands <a href="http://msdn.microsoft.com/en-us/library/system.console.write.aspx">Console.Write</a> and <a href="http://msdn.microsoft.com/en-us/library/system.console.read.aspx">Console.Read</a>.</p>
<p>Let's look at output (the . command) first. The C# code we're converting is a one-liner:</p>
<pre class="prettyprint lang-cs">
Console.Write((char)memory[pointer]);
</pre>
<p>As memory[pointer] is a byte, we have to cast it to char to write it to the console. In IL, the line looks like this:</p>
<pre class="prettyprint">
IL_0000:  ldsfld     uint8[] BFHelloWorldCSharp.Program::memory
IL_0005:  ldsfld     int16 BFHelloWorldCSharp.Program::pointer
IL_000a:  ldelem.u1
IL_000b:  call       void [mscorlib]System.Console::Write(char)
</pre>
<p>We already know what the two ldsfld commands to: They load the static field onto the evaluation stack. Now, <a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.ldelem_u1.aspx">ldelem.u1</a> is a new command and this is our cast to char. To quote the Documentation:</p>
<blockquote><p>
Loads the element with type unsigned int8 at a specified array index onto the top of the evaluation stack as an int32.
</p></blockquote>
<p>In other words, ldelem.u1 expects to load an Unsigned 8-Bit Integer which is a byte. You may wonder where the cast is, as char is a 16-Bit Unsigned Integer (=UTF-16 Unicode Character). So how is that possible? Well, <a href="http://www.ecma-international.org/publications/standards/Ecma-335.htm">ECMA-335</a> contains the answer in Partition III, Section 1.6 Implicit argument coercion:</p>
<blockquote><p>
While the CLI operates only on 6 types (int32, native int, int64, F, O, and &#038;) the metadata supplies a much richer model for parameters of methods. When about to call a method, the CLI performs implicit type conversions, detailed in the following table.
</p></blockquote>
<p>Translation: If the Parameter on the Stack is an int32 (which it is according to ldelem.u1), then the CLI will implicitly convert it to char if calling a method that wants a char.</p>
<p>The method call itself is then simply a call to static method Write in class System.Console in assembly mscorlib which returns void. The arguments to the method are taken from the evaluation stack. If a method takes multiple arguments, they have to be pushed in the correct order: First argument first.</p>
<p>That's the . command: Get the value of memory[pointer], call Console.Write with it. What about the , command to read a line?</p>
<p>In C#, this is again a one-liner:</p>
<pre class="prettyprint lang-cs">
memory[pointer] = (Byte)Console.Read();
</pre>
<p>while in IL this is a few lines more:</p>
<pre class="prettyprint">
IL_0000:  ldsfld     uint8[] BFHelloWorldCSharp.Program::memory
IL_0005:  ldsfld     int16 BFHelloWorldCSharp.Program::pointer
IL_000a:  call       int32 [mscorlib]System.Console::Read()
IL_000f:  conv.u1
IL_0010:  stelem.i1
</pre>
<p>Once again, we start by loading our array and the index into it onto the stack. However, we are not doing anything with them right now. Instead, we call Console.Read which returns an int32. According to the documentation of the <a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.call.aspx">call command</a>, The return value is pushed onto the stack.</p>
<p>So now our stack contains three values: The array, the current index and the return value of Console.Read (as Console.Read doesn't take parameters our memory &#038; pointer are still on the stack). <a href="http://msdn.microsoft.com/en-us/library/18aw813t.aspx">conv.u1</a> takes the Int32, converts it to UInt8 (that's the cast to byte in the method) and puts it on the stack again.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.stelem_i1.aspx">stelem.i1</a> is a new command:</p>
<blockquote><p>
Replaces the array element at a given index with the int8 value on the evaluation stack.
</p></blockquote>
<p>So this pops off the value, the index and the array and replaces the element. This is equivalent of calling <a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.ldelema.aspx">ldelema</a> followed by the operation that pushes the new value to the stack followed by <a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.stobj.aspx">stobj</a> but only takes one instruction if the correct values are on the stack.</p>
<p>In Part 5, I'll finish the command introduction with the [ and ] command (explaining how a while-loop works) and then we finally build our compiler!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stum.de/2010/04/27/writing-a-bf-compiler-for-net-part-4-and/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How the Async support in RestSharp can help with Report Generation</title>
		<link>http://www.stum.de/2010/04/20/how-the-async-support-in-restsharp-can-help-with-report-generation/</link>
		<comments>http://www.stum.de/2010/04/20/how-the-async-support-in-restsharp-can-help-with-report-generation/#comments</comments>
		<pubDate>Tue, 20 Apr 2010 18:00:54 +0000</pubDate>
		<dc:creator>mstum</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[RestSharp]]></category>

		<guid isPermaLink="false">http://www.stum.de/?p=831</guid>
		<description><![CDATA[I've been using RestSharp in the past weeks for some backend tools, mainly because REST is easy to implement and I like the Deserialization support that comes with it. One of the reasons I wanted to add async support is because I wanted to write a monitoring application. I am using Microsoft Chart Controls, and [...]]]></description>
			<content:encoded><![CDATA[<p>I've been using <a href="http://github.com/johnsheehan/RestSharp">RestSharp</a> in the past weeks for some backend tools, mainly because REST is easy to implement and I like the Deserialization support that comes with it. One of the reasons I wanted to add async support is because I wanted to write a monitoring application.</p>
<p>I am using <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=130F7986-BF49-4FE5-9CA8-910AE6EA442C&#038;displaylang=en">Microsoft Chart Controls</a>, and I have a server that accepts REST Requests in the form /reports/health/{entity} to return something like this:</p>
<pre class="prettyprint lang-xml">
&lt;healthdata>
    &lt;healthindex>73&lt;/healthindex>
&lt;/healthdata>
</pre>
<p>I don't know which entities are being pinged at compile time. I can't even put them in a config file, as someone might add or remove entities while the application is still running. So I decided to have an architecture with a Timer, a Request Dispatcher and a Response Handler.</p>
<p>The Timer executes every 5 seconds, gets the current list of entities and calls the Request Dispatcher:</p>
<pre class="prettyprint lang-cs">
private void timer1_Tick(object sender, EventArgs e)
{
    foreach(string entity in GetEntities()){
        DispatchRequest(entity);
    }
}
</pre>
<p>The Request Dispatcher creates a new RestRequest and a custom State Object. The state object will be important later, for now lets just note that it contains the entityname and the time the request was sent.</p>
<pre class="prettyprint lang-cs">
private void DispatchRequest(string entityName)
{
    var rq = new RestRequest("health/{entity}", Method.GET);
    rq.AddParameter("entity", entityName, ParameterType.UrlSegment);

    var state = new ServiceState {Entity = entityName, RequestDateUtc = DateTime.UtcNow};
    _client.BeginExecute&lt;healthdata>(rq, HandleResponse, state);
}
</pre>
<p>The Request Dispatcher doesn't care what happens afterwards, it just happily fires new requests all the time and tells BeginExecute to call HandleResponse afterwards.</p>
<pre class="prettyprint lang-cs">
private void HandleResponse(IAsyncResult res)
{
    // Note: This assumes the response is always good. In reality, you want to
    // check response.ResponseStatus and act accordingly
    var result = (AsyncResult) res;
    var caller = (RequestExecuteCaller&lt;healthdata>) result.AsyncDelegate;
    var state = res.AsyncState as ServiceState;
    var response = caller.EndInvoke(res);
    AddDataToChart(state.Entity, response.Data.healthindex, state.RequestDateUtc);
}
</pre>
<p>Here comes our state object into play. If you look at the XML from the server above, you see that it doesn't echo the Entity Name. As HandleResponse handles all responses, it has to know which response corresponds to which server. Also, async operations can come in a different order than the one executed - I may send requests for entities s1, s2, s3, s4 and receive them back in the order s3, s1, s4, s2. If the timer interval is too small and the server latency is too high, I might even receive a later request for s2 before an earlier one - it's pure anarchy.</p>
<p>That's why I've passed a state object to BeginExecute, as this allowed me to capture the entity name and the exact Date of the request. So all that HandleResponse has to do is to get the state and healthdata and call the function that adds the data to the chart with precise information about the Time, the Entity and it's health.</p>
<p>All without ever locking the UI or without giving the dispatcher or the handler too much work that they shouldn't be doing.</p>
<p><img src="http://www.stum.de/wp-content/uploads/2010/04/RSAsync.jpg" alt="" title="RSAsync" width="620" height="394" class="aligncenter size-full wp-image-832" /><br />
<small>(Excuse the horrible colors, I'm only a developer <img src='http://www.stum.de/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> )</small></p>
]]></content:encoded>
			<wfw:commentRss>http://www.stum.de/2010/04/20/how-the-async-support-in-restsharp-can-help-with-report-generation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How Optional Parameters work, why they can be dangerous, and why they work in .net 2/3 as well</title>
		<link>http://www.stum.de/2010/04/19/how-optional-parameters-work-why-they-can-be-dangerous-and-why-they-work-in-net-23-as-well/</link>
		<comments>http://www.stum.de/2010/04/19/how-optional-parameters-work-why-they-can-be-dangerous-and-why-they-work-in-net-23-as-well/#comments</comments>
		<pubDate>Mon, 19 Apr 2010 18:36:59 +0000</pubDate>
		<dc:creator>mstum</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://www.stum.de/?p=823</guid>
		<description><![CDATA[One of the changes I really like in Visual Studio 2010 are optional parameters to method. Basically they allow you to specify a default value for each parameter and thus reduce the number of overloads to a method. Make sure to read to the end as there is a huge word of caution regarding optional [...]]]></description>
			<content:encoded><![CDATA[<p>One of the changes I really like in Visual Studio 2010 are optional parameters to method. Basically they allow you to specify a default value for each parameter and thus reduce the number of overloads to a method. Make sure to read to the end as there is a <strong>huge word of caution regarding optional parameters</strong>.</p>
<p>Instead of having this:</p>
<pre class="prettyprint lang-cs">
private static string SomeMethod(int value)
{
    return SomeMethod(value, "Was Empty");
}

private static string SomeMethod(int value, string data)
{
    return string.Format("{0}: {1}", value, data);
}
</pre>
<p>You can just have this:</p>
<pre class="prettyprint lang-cs">
// static because it's a console app, no extra magic
private static string OptionalMethod(int value, string data = "Was Empty")
{
    return string.Format("{0}: {1}", value, data);
}
</pre>
<p>The nice thing about this feature is that it also works with .net 2/3. Why? Because it is implemented like this:</p>
<pre class="prettyprint lang-cs">
private static string OptionalMethod(int value,
                          [Optional, DefaultParameterValue("Was Empty")] string data)
{
    return string.Format("{0}: {1}", value, data);
}
</pre>
<p>Looks like a normal method (the longest overload) with some attributes. Are those attributes the magic? No, it's much simpler.<br />
If this is your calling code:</p>
<pre class="prettyprint lang-cs">
Console.WriteLine(OptionalMethod(1));
Console.WriteLine(OptionalMethod(2,"Test"));
</pre>
<p>Then this is how it looks in the compiled assembly:</p>
<pre class="prettyprint lang-cs">
Console.WriteLine(OptionalMethod(1, "Was Empty"));
Console.WriteLine(OptionalMethod(2, "Test"));
</pre>
<p>As you see, the compiler changes the method call to put in all optional parameters into the caller. This explains why this works with pre-.net 4 applications. However, this also explains the huge warning I want to give:</p>
<p><strong>Changing the optional parameter value will not change the behavior of your callers!</strong></p>
<p>Imagine you want to change the value to "No value specified". With the overload solution this is trivial:</p>
<pre class="prettyprint lang-cs">
private static string SomeMethod(int value)
{
    return SomeMethod(value, "No value specified");
}
</pre>
<p>Recompile your provider assembly and every consumer who uses that overload will get the new value. However, with optional parameters you have to re-compile each and every consumer assembly as well, so changing an optional parameter is a big, breaking change.</p>
<p>Does that mean that Optional Parameters are evil and should be avoided at all costs? Some people might think so, but I think they are useful for variables that almost never change. Think about a function like <code>SendMail(string server, int port = 25)</code>.</p>
<p><del datetime="2010-04-19T19:11:14+00:00">However, I do object that ReSharper 5 offers the hint to introduce Optional Parameters too lightly:</del><br />
<img src="http://www.stum.de/wp-content/uploads/2010/04/RS5OP.png" alt="" title="RS5OP" width="635" height="117" class="aligncenter size-full wp-image-824" /></p>
<p><strong>Edit:</strong> I gave the ReSharper guys bad credit. If the method is declared as public, it does not offer that hint. Sorry guys for not double checking that! This then makes complete sense, as Optional Parameters are fine and safe for private/internal members.</p>
<p>I know too many people why blindly follow any advice that ReSharper give and that might see optional parameters as "Ohh, Shiny, no more Overloads!". Of course, you can argue that developers should know their stuff and deserve to fall hard on their face once they rolled it out as a big API and suddenly realize they have to recompile/redeploy dozens or hundreds of consumer assemblies because of a change. <del datetime="2010-04-19T19:11:14+00:00">I am however not a fan of this type of developer elitism and would have preferred if ReSharper would not show that hint by default.</del></p>
<p>Just my 2 cents though.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stum.de/2010/04/19/how-optional-parameters-work-why-they-can-be-dangerous-and-why-they-work-in-net-23-as-well/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Writing a BF Compiler for .net (Part 3: pointer++ and pointer&#8211;)</title>
		<link>http://www.stum.de/2010/04/19/writing-a-bf-compiler-for-net-part-3-pointer-and-pointer/</link>
		<comments>http://www.stum.de/2010/04/19/writing-a-bf-compiler-for-net-part-3-pointer-and-pointer/#comments</comments>
		<pubDate>Sun, 18 Apr 2010 23:09:45 +0000</pubDate>
		<dc:creator>mstum</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[brainfk]]></category>

		<guid isPermaLink="false">http://www.stum.de/?p=819</guid>
		<description><![CDATA[The last article gave an introduction to the concepts and we started looking at the memory[pointer]++/-- functions. Today is a quicky post to look at two other instructions, pointer++ and pointer-- or &#62; and &#60; in BF. Unsurprisingly, these are extremely simple operations, requiring only 5 IL Commands: IL_0000: ldsfld int16 BFHelloWorldCSharp.Program::pointer IL_0005: ldc.i4.1 IL_0006: [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://www.stum.de/2010/04/12/writing-a-bf-compiler-for-net-part-2-writing-bf-in-c-and-looking-at-the-il/">last article</a> gave an introduction to the concepts and we started looking at the memory[pointer]++/-- functions. Today is a quicky post to look at two other instructions, pointer++ and pointer-- or &gt; and &lt; in BF.</p>
<p>Unsurprisingly, these are extremely simple operations, requiring only 5 IL Commands:</p>
<pre>
  IL_0000:  ldsfld     int16 BFHelloWorldCSharp.Program::pointer
  IL_0005:  ldc.i4.1
  IL_0006:  add
  IL_0007:  conv.i2
  IL_0008:  stsfld     int16 BFHelloWorldCSharp.Program::pointer
</pre>
<p>ldsfld loads a static field onto the evaluation stack, ldc.i4.1 pushes the number 1 to the stack, add takes the two values from the stack and pushes the result back. conv.i2 converts the value on the stack (which is an Int32) to Int16 (2-Byte Int), pads it to be Int32 (as that is the smallest datatype possible on the stack) and pushes it back. stsfld then replaces the value in the static variable with the value from the stack.</p>
<p>As usual, pointer-- works the exact same way with the difference of using sub instead of add. One word of note: sub subtracts value2 from value1. While the order doesn't matter for add, it does for sub. Also note that add and sub do not detect overflow, so you can happily add 1 to Int16.MaxValue. If you want overflow checking, there is sub.ovf and add.ovf which throw an OverflowException.</p>
<p>With the 4 easy operations done, we will look at . and , next for input and output. Finally, we will look at [ and ]. After we have looked at the IL for each operation, we will write our compiler.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stum.de/2010/04/19/writing-a-bf-compiler-for-net-part-3-pointer-and-pointer/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Writing a BF Compiler for .net (Part 2: Writing BF in C# and looking at the IL)</title>
		<link>http://www.stum.de/2010/04/12/writing-a-bf-compiler-for-net-part-2-writing-bf-in-c-and-looking-at-the-il/</link>
		<comments>http://www.stum.de/2010/04/12/writing-a-bf-compiler-for-net-part-2-writing-bf-in-c-and-looking-at-the-il/#comments</comments>
		<pubDate>Mon, 12 Apr 2010 03:09:34 +0000</pubDate>
		<dc:creator>mstum</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[brainfk]]></category>

		<guid isPermaLink="false">http://www.stum.de/?p=812</guid>
		<description><![CDATA[In the last posting, we looked at BF as a language and how to write an interpreter in C#. The point of doing that was to understand what each function actually does. As I am no IL Expert, my second step was to write the Hello World BF Application as C#, that is one extremely [...]]]></description>
			<content:encoded><![CDATA[<p>In the <a href="http://www.stum.de/2010/04/09/writing-a-bf-compiler-for-net-part-1-explanation-of-the-language-and-interpreter-in-c/">last posting</a>, we looked at BF as a language and how to write an interpreter in C#. The point of doing that was to understand what each function actually does. As I am no IL Expert, my second step was to write the Hello World BF Application as C#, that is one extremely long function with each BF command spelled out. You can find the <a href="http://pastie.org/910801">full function here</a>. This is an Excerpt:</p>
<pre class="prettyprint">
static void Main(string[] args)
{
    memory[pointer]++;
    memory[pointer]++;
    memory[pointer]++;
    memory[pointer]++;
    memory[pointer]++;
    memory[pointer]++;
    memory[pointer]++;
    memory[pointer]++;
    memory[pointer]++;
    memory[pointer]++;
    while(memory[pointer] > 0)
    {
        pointer++;
        memory[pointer]++;
        memory[pointer]++;
        memory[pointer]++;
        // snipped
    }
    // snipped
}
</pre>
<p>As you see, we literally translated each instruction into a C# instruction. Compile this in Debug Mode, load it up in ildasm:<br />
<img src="http://www.stum.de/wp-content/uploads/2010/04/ildasmBF.png" alt="" title="ildasmBF" width="600" height="792" class="aligncenter size-full wp-image-813" /></p>
<p>Whoa, now were talking! Note that the ildasm will look different between Debug and Release modes due to optimizations. I prefer Debug to get an understanding how this works, and then later on Release mode to see the differences. The point is really to understand how this stuff looks in IL as we have to write IL ourselves later on.</p>
<p>So the first C# instruction is <code>memory[pointer]++</code>, which is a short way of saying <code>memory[pointer] = memory[pointer] + 1</code>. It is important that many language constructs and short-hand commands simply do not exist in IL - they are convenience functions in the C# compiler. Looking at the IL, our first C# instruction is now 9 IL instructions, starting from IL_0001 and ending at IL_0019.</p>
<pre class="prettyprint">
  IL_0001:  ldsfld     uint8[] BFHelloWorldCSharp.Program::memory
  IL_0006:  ldsfld     int16 BFHelloWorldCSharp.Program::pointer
  IL_000b:  ldelema    [mscorlib]System.Byte
  IL_0010:  dup
  IL_0011:  ldobj      [mscorlib]System.Byte
  IL_0016:  ldc.i4.1
  IL_0017:  add
  IL_0018:  conv.u1
  IL_0019:  stobj      [mscorlib]System.Byte
</pre>
<p>Let's quickly look at each command before I explain in Detail what is happening:</p>
<ol>
<li>Push the value of a static field 'memory' onto the evaluation stack.</li>
<li>Push the value of a static field 'pointer' onto the evaluation stack.</li>
<li>Load the address of the array element at a specified array index onto the top of the evaluation stack as type &#038; (managed pointer).</li>
<li>Copy the current topmost value on the evaluation stack, and then pushes the copy onto the evaluation stack.</li>
<li>Copy the value type object pointed to by an address to the top of the evaluation stack.</li>
<li>Push the integer value of 1 onto the evaluation stack as an int32.</li>
<li>Add two values and pushes the result onto the evaluation stack.</li>
<li>Convert the value on top of the evaluation stack to unsigned int8, and extends it to int32.</li>
<li>Copy a value of a specified type from the evaluation stack into a supplied memory address.</li>
</ol>
<p>That looks more complicated than it really is, especially if you don't know how CPUs usually work or never worked with Assembler. .net/IL is a Stack Based language, and functions work against this stack. For example, the Add instruction at address IL_0016 does not take parameters. Instead, it removes 2 elements from the stack, adds them, and pushes the result back to the stack. Be aware that most functions assume that the objects on the stack have the correct type - trying to push a string and an Int32 and calling Add will crash the CLR. Not all functions require their parameters on the stack, but many do - you can find an Overview of each function in Partition III of the <a href="http://www.ecma-international.org/publications/standards/Ecma-335.htm">ECMA-335 standard</a> or in the <a href="http://msdn.microsoft.com/en-us/library/812xyxy2.aspx">OpCodes Fields</a>.</p>
<p>Anyway, let's dissect the instruction and look at what's happening.<br />
<strong>1. Getting memory[pointer]</strong><br />
In order to increment the value at memory[pointer], we first need to get it. This is the job of the ldelema instruction at IL_000a. To quote from <a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.ldelema.aspx">the documentation</a>:<br />
<em>Loads the address of the array element at a specified array index onto the top of the evaluation stack as type &#038; (managed pointer).</em></p>
<p>So this function requires an array and an array index, and it gives us a managed pointer to that element. It expects that we push the array and the index to the stack (in that order). It will then pop (remove) these two elements from the stack and pushes the pointer back to the array.</p>
<p>The ldsfld function pushes the value of a static field onto the stack (pointer and memory were declared static). So we first push the memory array to the stack, and then the value of the pointer variable.</p>
<p>Here is a diagram:<br />
<img src="http://www.stum.de/wp-content/uploads/2010/04/BF-1.jpg" alt="" title="BF-1" width="528" height="240" class="aligncenter size-full wp-image-814" /></p>
<p><strong>2. Incrementing the value</strong><br />
Now we have a pointer to memory[pointer], but we need to increase it. That is what the next 4 instructions do. The important function is add at IL_0017, which takes two values from the stack and adds them. But at the moment, we only have the managed pointer on the stack. We first need to get the <em>value</em> of memory[pointer] to the stack. This is that ldobj at IL_0011 does: It gets the address of the value from the stack and pushes the actual value onto it. Note that this is now just a byte - it has no connection to the memory array, it is simply a number.</p>
<p>Before that, you might wonder what the dup instruction does: It simply creates a copy of the topmost value on the stack, effectively duplicating it. This might seem useless for the addition, but it is required later. For now, just ignore it.</p>
<p>Now that we have the current value of the memory[pointer], we need the second number to perform the addition. As ++ is just a shorthand for +1, we need to push the number 1 to the stack. To push an Int32 value to the stack, you can use the ldc.i4 instruction which pushes the supplied number to the stack. However, there are also shorthand commands for some numbers, and the command ldc.i4.1 pushes the number 1 to the stack. (I do not know if these commands exist for performance or for code size reasons, also I strongly believe the latter. ldc.i4.1 is a 1-byte command, whereas ldc.i4 requires 5 bytes: 1 for the command and 4 bytes for the Int32 value to push).</p>
<p>So now we have the current value of memory[pointer] and the number 1 on the stack, and the Add function pops them off, performs the addition and pushes the result.</p>
<p>A diagram for this part:<br />
<img src="http://www.stum.de/wp-content/uploads/2010/04/BF-2.jpg" alt="" title="BF-2" width="528" height="240" class="aligncenter size-full wp-image-815" /></p>
<p>Just a slight note: The 1 at the end is not the same 1 as the one before. Add removes 0 and 1 from the stack, "generates a new 1" through performing 0 + 1 and pushes that to the stack.</p>
<p><strong>3. Storing the value in the array again</strong><br />
We performed the addition, but as a result we simply have the number 1 on the stack now - memory[pointer] is still 0 though! The last two instructions take care of saving it back. Now, the number 1 on the stack is an Int32, but we have an array of Bytes. The first instruction, conv.u1 at IL_0018 gets a value off the stack, converts it to an unsigned 8-bit integer (which is exactly what a Byte in .net is), adds padding to Int32 and pushes it back to the stack. This might seem silly, but the evaluation stack only holds 4- or 8-byte integers (See Partition III, 1.1 Data Types of ECMA-335). The conv instruction makes sure that the actual data is stored in the "correct" bits (the ones later used to read the value), while the other 24 bits are merely padding to make it an Int32.</p>
<p>stobj copies the value to the desired memory location. You may now understand why we had the dup instruction at IL_0010: We need to know <em>where</em> to copy the value to, but the ldobj object removed the address from the stack already at IL_0011! So by duplicating the address, we can give it to both functions (otherwise we would have to do the lookup in the first three lines again).<br />
<img src="http://www.stum.de/wp-content/uploads/2010/04/BF-3.jpg" alt="" title="BF-3" width="312" height="240" class="aligncenter size-full wp-image-816" /></p>
<p>And that is the memory[pointer]++ C# instruction in IL! I know it looks scary at first, but it's rather simple and logical once you understood how this stuff works internally. Remember, at some point each programming language needs to be translated into very specific CPU instructions. We are not at that level (this is what the CLR and it's JITter does), but we are at a fairly low level. Remember, we have to write a compiler for this, so we need to understand a) what is happening and b) why it is happening. Making those diagrams helped me a lot, especially because I didn't understand the use of the dup instruction at first.</p>
<p>Now that we know how this instruction works, we will look at the other 7 BF Instructions. I can already tell you how memory[pointer]-- works: It is <em>exactly</em> the same function, with the difference of using sub instead of add at IL_0017, so no need for an article of it's own.</p>
<p>The two pointer operations (pointer++ and pointer--) will be described in the next article.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stum.de/2010/04/12/writing-a-bf-compiler-for-net-part-2-writing-bf-in-c-and-looking-at-the-il/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Writing a BF Compiler for .net (Part 1: Explanation of the language and interpreter in C#)</title>
		<link>http://www.stum.de/2010/04/09/writing-a-bf-compiler-for-net-part-1-explanation-of-the-language-and-interpreter-in-c/</link>
		<comments>http://www.stum.de/2010/04/09/writing-a-bf-compiler-for-net-part-1-explanation-of-the-language-and-interpreter-in-c/#comments</comments>
		<pubDate>Fri, 09 Apr 2010 06:24:20 +0000</pubDate>
		<dc:creator>mstum</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[brainfk]]></category>

		<guid isPermaLink="false">http://www.stum.de/?p=800</guid>
		<description><![CDATA[Today I'm starting a small series about how to write a Compiler to .net IL. I wanted to understand IL better and wanted to learn how .net really works. Even though I'm a Web Developer (which usually means working on a much higher level of abstraction), at some point there is this impossible issue that [...]]]></description>
			<content:encoded><![CDATA[<p>Today I'm starting a small series about how to write a Compiler to .net IL. I wanted to understand IL better and wanted to learn how .net really works. Even though I'm a Web Developer (which usually means working on a much higher level of abstraction), at some point there is this impossible issue that has no cause and no resolution and where Reflector and WinDbg have to come in.</p>
<p>My main focus is understanding IL, not implementing a language. So I picked an extremely simple but otherwise complete language - <a href="http://en.wikipedia.org/wiki/Brainfuck">Brainf**k</a> (abbreviated BF from here on). Yes, it is a very esoteric language, but as said, focus is on the IL Part, not the actual language.</p>
<p>BF only has 8 instructions, represented by a single character each:</p>
<table>
<tr>
<td style="width: 20px">&gt;</td>
<td>Moves the memory pointer forward</td>
</tr>
<tr>
<td style="width: 20px">&lt;</td>
<td>Moves the memory pointer backwards</td>
</tr>
<tr>
<td style="width: 20px">+</td>
<td>Increments the value at the current memory pointer</td>
</tr>
<tr>
<td style="width: 20px">-</td>
<td>Decrements the value at the current memory pointer</td>
</tr>
<tr>
<td style="width: 20px">.</td>
<td>Outputs the value at the current memory pointer</td>
</tr>
<tr>
<td style="width: 20px">,</td>
<td>Reads a single byte from some input, storing it at the memory pointer</td>
</tr>
<tr>
<td style="width: 20px">[</td>
<td>Go to the next instruction if the byte at the memory pointer is not 0, otherwise move it past the matching ] instruction</td>
</tr>
<tr>
<td style="width: 20px">]</td>
<td>Go to the instruction after the matching [ if the byte at the memory pointer is not 0, else move it past the ]</td>
</tr>
</table>
<p>So basically with BF you have three objects: Some Memory, a Pointer to a byte in the Memory and an instruction pointer. The memory can be implemented as a simple byte array and the memory pointer as an index into it.</p>
<p>Let's say we have 4 bytes of memory. At the beginning, everything is initialized to 0 (P = Memory Pointer):<br />
<code>Memory: 00 00 00 00 P:0</code></p>
<p>Now we execute the following code:<br />
<code>++&gt;+++&gt;++++&gt;+&lt;-</code></p>
<p>The result is this:<br />
<code>Memory: 02 03 03 01 P:2</code></p>
<p>The [ and ] instructions are more complicated, but essentially they form a while loop - <code>while(memory[pointer] != 0) { // instructions between the brackets }</code>. One example is to increase the value of a register without having many + signs. Let's say we want to increase memory[1] to 25. For that, we use memory[0] as a counter:<br />
<code>+++++[>+++++<-]</code></p>
<p>After running this, the memory will look like this:<br />
<code>Memory: 00 19 00 00 P:0</code><br />
(Remember that this is hex, so 19h is 25 decimal)</p>
<p>What did we do? We increased memory[0] to 5. Then we entered a while-block. First, we move the memory pointer to memory[1] and increase it 5 times, to 5. Then we move back to memory[0] and decrease it to 4. The ] then checks if memory[0] is 0, which it isn't, so we return to the instruction after the [, which means we move again to memory[1], increase it 5 more times, move back to memory[0], decrease it to 3 and repeat until memory[0] is 0.</p>
<p>As said, not terribly complicated once you understood how the brackets and the memory pointer work. Let's look at Hello World in BF:<br />
<code>++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.</code><br />
(Note that this needs 5 bytes of memory instead of 4)</p>
<p>This looks scary, but is also quite simple if you are familiar with <a href="http://en.wikipedia.org/wiki/ASCII">ASCII Encoding</a>. The . command outputs the value at the memory pointer to the console and the console then needs to decide what to do with it. Again, everything in a PC is essentially just a stream of bytes, and a byte can mean different things to different applications. The Console tries to display the byte by looking up which character maps to a byte. In ASCII, the letter H is mapped to byte 48h or 72 decimal. So if you want to display the letter H, you need to increase the value 72 times.</p>
<p>The Hello World example uses the while loop to save a lot of +. Also instead of using 13 Bytes (The Letters H, e, l, l, o, [space], W, o, r, l, d, !, [line break]), the example only uses 5 bytes by reusing existing memory locations. Look up the values for each letter in the ASCII table and it should become clear how this works. The Wikipedia Article contains a lot more explanations.</p>
<p>Now, before I started building a real compiler, I first wanted to see how this would work and could be implemented, so I started with an interpreter in C# that reads text from one TextBox and outputs results into another one (no support for the , instruction here though). The code for that is somewhat naive, but it helps understanding how this could work:</p>
<pre class="prettyprint">
byte[] memory = new byte[Int16.MaxValue];
Int16 memoryPointer = 0;

private void Execute(char[] code)
{
    int instructionPointer = 0;
    while (instructionPointer &lt; code.Length)
    {
        var currentCommand = code[instructionPointer];
        instructionPointer++;
        switch (currentCommand)
        {
            case '>':
                memoryPointer++;
                break;
            case '&lt;':
                memoryPointer--;
                break;
            case '+':
                memory[memoryPointer]++;
                break;
            case '-':
                memory[memoryPointer]--;
                break;
            case '.':
                // Weird casting because AppendText wants a string, but we have to
                // convert the byte to a char first.
                textBox2.AppendText(((char)memory[memoryPointer]).ToString());
                break;
            case ',':
                // read 1 byte of input - not implemented
                break;
            case '[':
                int currentIndex = instructionPointer;
                int bracketCounter = 1;
                while (bracketCounter > 0 &#038;&
                       instructionPointer &lt; code.Length &#038;&
                       code[instructionPointer] > 0)
                {
                    if (code[instructionPointer] == '[') bracketCounter++;
                    if (code[instructionPointer] == ']') bracketCounter--;
                    instructionPointer++;
                }
                if (bracketCounter == 0)
                {
                    // Change previous ] to \0 so that the recursive call
                    // returns at the end of the block
                    code[instructionPointer - 1] = '\0';
                    while(memory[memoryPointer] > 0) {
                       Execute(code.Skip(currentIndex).ToArray());
                    }
                    code[instructionPointer - 1] = ']';
                    break;
                }
                break;
            case ']':
                // The ] bracket is normally handled as part of the [ case above
                throw new InvalidOperationException("Unbalanced Brackets");
                break;
            case '\0':
                return;
        }
    }
}
</pre>
<p>First, we declare our memory. As this is .net and I didn't want to use unsafe code/pointers, I'm declaring an Array of Bytes. The total size is 32767 bytes. Then I declare a memoryPointer which is just an index into the memory array (it's not a pointer in the traditional sense, I just called it that).</p>
<p>Then we have the Execute method, which takes an array of bytes - the BF code. We iterate through this array and perform the appropriate action for each instruction. This should be really straight-forward, except for the [, ] and \0 cases. If we encounter a [, we go all the way to the end in order to find until the instruction pointer hits the end of the code or a 0-byte. The bracketCounter is there for us to make sure our brackets are balanced - you can nest brackets, but they have to be balanced. <code>[++[++]++</code> is illegal code as the first [ does not have a matching ]. As soon as our bracketCounter hits 0 again, we stop this loop. The important side effect of this: The instructionPointer is now behind the ].</p>
<p>We replace the ] with a 0-byte and recursively call the Execute function with the fraction of the code after the [ (that's the job of the currentIndex variable: Remember where the [ was). The recursive call will return as soon as it hits the 0-byte. The while-loop then repeats this recursive call until the memory at the pointer is 0 and re-inserts the ].</p>
<p>If you execute this in a WinForms application, your textBox2 should display <code>Hello World!</code>.</p>
<p>Phew, I hope you could follow me all the way down here and got an understanding of how BF works. Tomorrow we will translate the BF code into C# code and look at the generated IL, and then I will post articles explaining what each of these instructions do, how IL OpCodes work, what the fact that .net is Stack based actually means, and then we will have a real BF -> .net Compiler.</p>
<p>Expect a fun little series <img src='http://www.stum.de/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.stum.de/2010/04/09/writing-a-bf-compiler-for-net-part-1-explanation-of-the-language-and-interpreter-in-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Do we need an open source alternative to Reflector?</title>
		<link>http://www.stum.de/2010/04/08/do-we-need-an-open-source-alternative-to-reflector/</link>
		<comments>http://www.stum.de/2010/04/08/do-we-need-an-open-source-alternative-to-reflector/#comments</comments>
		<pubDate>Thu, 08 Apr 2010 06:46:52 +0000</pubDate>
		<dc:creator>mstum</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://www.stum.de/?p=796</guid>
		<description><![CDATA[I just started .net Reflector and got the update prompt: Nothing special here, except that both options are bad. Clicking Yes gives me this window: And clicking No prevents Reflector from starting. So basically I can't use Reflector unless I download a new version manually or disconnect my PC from the internet or somehow else [...]]]></description>
			<content:encoded><![CDATA[<p>I just started .net Reflector and got the update prompt:</p>
<p><img src="http://www.stum.de/wp-content/uploads/2010/04/Reflector1.png" alt="" title="Reflector1" width="476" height="171" class="aligncenter size-full wp-image-797" /></p>
<p>Nothing special here, except that both options are bad. Clicking Yes gives me this window:<br />
<img src="http://www.stum.de/wp-content/uploads/2010/04/Reflector2.png" alt="" title="Reflector2" width="489" height="171" class="aligncenter size-full wp-image-798" /></p>
<p>And clicking No <strong>prevents Reflector from starting</strong>. So basically I can't use Reflector unless I download a new version manually or disconnect my PC from the internet or somehow else suppress the update check. This got me thinking about the Status of .net Reflector.</p>
<p>It's an excellent tool, to the point it's almost essential for many developers. Lutz Roeder did a fantastic job with it, and Red Gate is continuing to improve it. But the tool is not free, and the message above just had me realize again that it can be shut down any time. Of course, Red Gate has promised to keep a free version and I have no reason to think they are not truthful, but at the same time I've seen many companies shutting down free products for whatever reason. This would be absolutely their right, but it got me thinking: Is .net Reflector <em><a href="http://en.wikipedia.org/wiki/Too_big_to_fail">"too big to fail"</a></em>? </p>
<p>Should there be an Open Source Alternative? Or am I too heavily biased (being a SharePoint developer) and overestimate the importance of it?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stum.de/2010/04/08/do-we-need-an-open-source-alternative-to-reflector/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Experimental Async support for RestSharp</title>
		<link>http://www.stum.de/2010/04/02/experimental-async-support-for-restsharp/</link>
		<comments>http://www.stum.de/2010/04/02/experimental-async-support-for-restsharp/#comments</comments>
		<pubDate>Fri, 02 Apr 2010 07:47:31 +0000</pubDate>
		<dc:creator>mstum</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://www.stum.de/?p=789</guid>
		<description><![CDATA[I have just commited a change to my ASync branch on my fork of RestSharp on GitHub. I want to do some more testing first before I ask John Sheehan to pull in the change. The new files are IAsyncRestClient.cs and AsyncRestClient.cs which derive from their normal (synchronous) implementations. Edit: This change was merged into [...]]]></description>
			<content:encoded><![CDATA[<p><del datetime="2010-04-19T17:07:10+00:00">I have just commited a change to my <a href="http://github.com/mstum/RestSharp/tree/ASync">ASync branch</a> on my fork of <a href="http://restsharp.org/">RestSharp</a> on GitHub. I want to do some more testing first before I ask John Sheehan to pull in the change</del>. The new files are IAsyncRestClient.cs and AsyncRestClient.cs which derive from their normal (synchronous) implementations. <ins datetime="2010-04-19T17:07:10+00:00"><strong>Edit:</strong> This change was merged into the <a href="http://github.com/johnsheehan/RestSharp">official RestSharp source code</a> and is documented on the <a href="http://wiki.github.com/johnsheehan/RestSharp/async-execution">RestSharp Wiki</a>. There was a major bug fix to the functionality on April 18, 2010.</ins></p>
<p>Anyway, here are the examples on how to use it. I assume you know what the state parameter on an Async call does, if not just set it to null.</p>
<pre class="prettyprint">
var client = new AsyncRestClient(serviceUrl);
var request = new RestRequest(Method.GET);

// Synchronous Execution still works - AsyncRestClient derives from RestClient
var SyncResponse = client.Execute(request);
Console.WriteLine(response.Content);

// But Asynchronous Execution is much nicer!
// Method 1: Waiting for an Asynchronous Call with EndExecute
var asyncRes1 = client.BeginExecute(request, null, "some state, can be null");
var responseAsync1 = client.EndExecute(asyncRes1);
Console.WriteLine(responseAsync1.Content);

// Method 2: Polling for Asynchronous Call Completion
var asyncRes2 = client.BeginExecute(request, null, "some state");
while (!asyncRes2.IsCompleted)
{
    Console.Write(".");
    System.Threading.Thread.Sleep(100);
}
var responseAsync2 = client.EndExecute(asyncRes2);
Console.WriteLine(responseAsync2.Content);

// Method 3: Waiting for an Asynchronous Call with WaitHandle
var asyncRes3 = client.BeginExecute(request, null, "some state");
asyncRes3.AsyncWaitHandle.WaitOne();
var responseAsync3 = client.EndExecute(asyncRes3);
Console.WriteLine(responseAsync3.Content);

// Method 4: Using a Callback Method
static void Main(string[] args)
{
    var asyncRes4 = client.BeginExecute(request, EndResponse, "some state");
    Console.ReadLine();
}

static void EndResponse(IAsyncResult res)
{
    var result = (AsyncResult)res;
    var caller = (RequestExecuteCaller)result.AsyncDelegate;
    var response = caller.EndInvoke(res);
    Console.WriteLine("AsyncResult: "+response.Content);
}

// This also works for the Execute&lt;T> method, without callback...
var asyncResT = client.BeginExecute&lt;MyDTOClass>(request, null, "some state");
var responseAsyncT = client.EndExecute&lt;MyDTOClass>(asyncResT);
Console.WriteLine(responseAsyncT.Data.SomePropertyInMyClass);

// ...and with Callback
static void Main(string[] args)
{
    var asyncResTC = client.BeginExecute&lt;MyDTOClass>(request, EndResponse, "some state");
    Console.ReadLine();
}

static void EndResponse(IAsyncResult res)
{
    var result = (AsyncResult)res;
    var caller = (RequestExecuteCaller&lt;MyDTOClass>)result.AsyncDelegate;
    var response = caller.EndInvoke(res);
    Console.WriteLine("AsyncResult: "+response.Data.SomePropertyInMyClass);
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.stum.de/2010/04/02/experimental-async-support-for-restsharp/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>A slight Nitpick/Improvement for Tekpubs Video about ASP.net MVC Routing</title>
		<link>http://www.stum.de/2010/03/28/a-slight-nitpickimprovement-for-tekpubs-video-about-asp-net-mvc-routing/</link>
		<comments>http://www.stum.de/2010/03/28/a-slight-nitpickimprovement-for-tekpubs-video-about-asp-net-mvc-routing/#comments</comments>
		<pubDate>Sun, 28 Mar 2010 10:49:47 +0000</pubDate>
		<dc:creator>mstum</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[asp.net mvc]]></category>

		<guid isPermaLink="false">http://www.stum.de/?p=779</guid>
		<description><![CDATA[Tekpubs series about ASP.net MVC 2 is really useful and has tons and tons of great tips and code samples, and the episode about Routing (#12) is no exception. However, there is one thing I really didn't like about it. Around 30 Minutes in when discussing SEO Optimizations, they show a great tip how to [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://tekpub.com/preview/aspmvc">Tekpubs series</a> about ASP.net MVC 2 is really useful and has tons and tons of great tips and code samples, and the episode about Routing (#12) is no exception. However, there is one thing I really didn't like about it.</p>
<p>Around 30 Minutes in when discussing SEO Optimizations, they show a great tip how to enforce canonical URLs. Unfortunately, they do it by modifying the Response object directly. Basically the code looks like</p>
<pre class="prettyprint lang-cs">
// This snippet doesn't make much sense if you haven't
// watched the Episode, sorry.
public ViewResult Details(int id)
{
    //snipped some parts
    EnforceCanonicalUrl(jobAd.DetailsRouteValues());
    return View(jobAd);
}

private void EnforceCanonicalUrl(RouteValueDictionary routeValues)
{
    if(someCheckFails){
        Response.RedirectLocation = someLocation;
        Response.StatusCode = (int)HttpStatusCode.MovedPermanently;
        Response.End();
    }
}
</pre>
<p>This doesn't follow the MVC pattern, and the speaker even acknowledges it in the video as it makes unit testing hard. The proper way is to return an ActionResult from the ControllerAction instead. As I happen to have already written a <a href="http://www.stum.de/2008/10/22/permanentredirectresult/">PermanentRedirectResult</a>, my suggestion to improve this code is this:</p>
<pre class="prettyprint lang-cs">
public ActionResult Details(int id)
{
    //snipped some parts
    var enforcedResult = EnforceCanonicalUrl(jobAd.DetailsRouteValues());
    // As View and enforcedResult have different types, I cannot use the ?? operator
    if(enforcedResult != null) return enforcedResult;
    return View(jobAd);
}

private PermanentRedirectResult EnforceCanonicalUrl(RouteValueDictionary routeValues)
{
    if(someCheckFails){
        return new PermanentRedirectResult(canonicalPathAndQuery);
    } else {
       return null;
    }
}
</pre>
<p>So I changed the return type of the controller action to ActionResult instead of ViewResult, and I gave EnforceCanonicalUrl a return type. This function now either returns null or a PermanentRedirectResult, and the controller action now checks for it. There are of course more ways to refine it, but it is in line with the ASP.net MVC pattern of having Controller Actions return ActionResults instead of modifying the Response directly.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stum.de/2010/03/28/a-slight-nitpickimprovement-for-tekpubs-video-about-asp-net-mvc-routing/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
