<?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>Phil&#039;s Version</title>
	<atom:link href="http://philsversion.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://philsversion.com</link>
	<description>A Software Development Blog</description>
	<lastBuildDate>Tue, 21 Feb 2012 22:10:08 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>OrderBy a string in Entity Framework</title>
		<link>http://philsversion.com/2012/02/21/orderby-a-string-in-entity-framework/</link>
		<comments>http://philsversion.com/2012/02/21/orderby-a-string-in-entity-framework/#comments</comments>
		<pubDate>Tue, 21 Feb 2012 22:10:08 +0000</pubDate>
		<dc:creator>Phil</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://philsversion.com/?p=342</guid>
		<description><![CDATA[I&#8217;ve just started using Entity Framework, and I&#8217;ve found that it really helps speed up development time when dealing with queries where performance isn&#8217;t a huge issue. I added to an existing project which needed to keep the EF classes isolated in the data layer. This made it difficult to pass in a sort order [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve just started using Entity Framework, and I&#8217;ve found that it really helps speed up development time when dealing with queries where performance isn&#8217;t a huge issue.</p>
<p>I added to an existing project which needed to keep the EF classes isolated in the data layer. This made it difficult to pass in a sort order without having a massive switch statement to deal with each of the options.</p>
<p>I solved this by building an OrderBy extension method that takes a string, and builds the sort expression using reflection. This means you can sort without having to know the actual type of what you&#8217;re ordering by.</p>
<p>Here&#8217;s the Gist:</p>
<div id="gist-1878868" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><br/></div><div class='line' id='LC2'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">public</span> <span class="k">static</span> <span class="n">IQueryable</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="n">OrderBy</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;(</span><span class="k">this</span> <span class="n">IQueryable</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="n">source</span><span class="p">,</span> <span class="kt">string</span> <span class="n">sortExpression</span><span class="p">)</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">{</span></div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">if</span> <span class="p">(</span><span class="n">source</span> <span class="p">==</span> <span class="k">null</span><span class="p">)</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">throw</span> <span class="k">new</span> <span class="nf">ArgumentNullException</span><span class="p">(</span><span class="s">&quot;source&quot;</span><span class="p">,</span> <span class="s">&quot;source is null.&quot;</span><span class="p">);</span></div><div class='line' id='LC6'><br/></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">if</span> <span class="p">(</span><span class="kt">string</span><span class="p">.</span><span class="n">IsNullOrEmpty</span><span class="p">(</span><span class="n">sortExpression</span><span class="p">))</span></div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">throw</span> <span class="k">new</span> <span class="nf">ArgumentException</span><span class="p">(</span><span class="s">&quot;sortExpression is null or empty.&quot;</span><span class="p">,</span> <span class="s">&quot;sortExpression&quot;</span><span class="p">);</span></div><div class='line' id='LC9'><br/></div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">var</span> <span class="n">parts</span> <span class="p">=</span> <span class="n">sortExpression</span><span class="p">.</span><span class="n">Split</span><span class="p">(</span><span class="sc">&#39; &#39;</span><span class="p">);</span></div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">var</span> <span class="n">isDescending</span> <span class="p">=</span> <span class="k">false</span><span class="p">;</span></div><div class='line' id='LC12'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">var</span> <span class="n">propertyName</span> <span class="p">=</span> <span class="s">&quot;&quot;</span><span class="p">;</span></div><div class='line' id='LC13'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">var</span> <span class="n">tType</span> <span class="p">=</span> <span class="k">typeof</span><span class="p">(</span><span class="n">T</span><span class="p">);</span></div><div class='line' id='LC14'><br/></div><div class='line' id='LC15'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">if</span> <span class="p">(</span><span class="n">parts</span><span class="p">.</span><span class="n">Length</span> <span class="p">&gt;</span> <span class="m">0</span> <span class="p">&amp;&amp;</span> <span class="n">parts</span><span class="p">[</span><span class="m">0</span><span class="p">]</span> <span class="p">!=</span> <span class="s">&quot;&quot;</span><span class="p">)</span></div><div class='line' id='LC16'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">{</span></div><div class='line' id='LC17'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">propertyName</span> <span class="p">=</span> <span class="n">parts</span><span class="p">[</span><span class="m">0</span><span class="p">];</span></div><div class='line' id='LC18'><br/></div><div class='line' id='LC19'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">if</span> <span class="p">(</span><span class="n">parts</span><span class="p">.</span><span class="n">Length</span> <span class="p">&gt;</span> <span class="m">1</span><span class="p">)</span></div><div class='line' id='LC20'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">{</span></div><div class='line' id='LC21'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">isDescending</span> <span class="p">=</span> <span class="n">parts</span><span class="p">[</span><span class="m">1</span><span class="p">].</span><span class="n">ToLower</span><span class="p">().</span><span class="n">Contains</span><span class="p">(</span><span class="s">&quot;esc&quot;</span><span class="p">);</span></div><div class='line' id='LC22'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC23'><br/></div><div class='line' id='LC24'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">PropertyInfo</span> <span class="n">prop</span> <span class="p">=</span> <span class="n">tType</span><span class="p">.</span><span class="n">GetProperty</span><span class="p">(</span><span class="n">propertyName</span><span class="p">);</span></div><div class='line' id='LC25'><br/></div><div class='line' id='LC26'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">if</span> <span class="p">(</span><span class="n">prop</span> <span class="p">==</span> <span class="k">null</span><span class="p">)</span></div><div class='line' id='LC27'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">{</span></div><div class='line' id='LC28'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">throw</span> <span class="k">new</span> <span class="nf">ArgumentException</span><span class="p">(</span><span class="kt">string</span><span class="p">.</span><span class="n">Format</span><span class="p">(</span><span class="s">&quot;No property &#39;{0}&#39; on type &#39;{1}&#39;&quot;</span><span class="p">,</span> <span class="n">propertyName</span><span class="p">,</span> <span class="n">tType</span><span class="p">.</span><span class="n">Name</span><span class="p">));</span></div><div class='line' id='LC29'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC30'><br/></div><div class='line' id='LC31'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">var</span> <span class="n">funcType</span> <span class="p">=</span> <span class="k">typeof</span><span class="p">(</span><span class="n">Func</span><span class="p">&lt;,&gt;)</span></div><div class='line' id='LC32'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">.</span><span class="n">MakeGenericType</span><span class="p">(</span><span class="n">tType</span><span class="p">,</span> <span class="n">prop</span><span class="p">.</span><span class="n">PropertyType</span><span class="p">);</span></div><div class='line' id='LC33'><br/></div><div class='line' id='LC34'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">var</span> <span class="n">lambdaBuilder</span> <span class="p">=</span> <span class="k">typeof</span><span class="p">(</span><span class="n">Expression</span><span class="p">)</span></div><div class='line' id='LC35'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">.</span><span class="n">GetMethods</span><span class="p">()</span></div><div class='line' id='LC36'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">.</span><span class="n">First</span><span class="p">(</span><span class="n">x</span> <span class="p">=&gt;</span> <span class="n">x</span><span class="p">.</span><span class="n">Name</span> <span class="p">==</span> <span class="s">&quot;Lambda&quot;</span> <span class="p">&amp;&amp;</span> <span class="n">x</span><span class="p">.</span><span class="n">ContainsGenericParameters</span> <span class="p">&amp;&amp;</span> <span class="n">x</span><span class="p">.</span><span class="n">GetParameters</span><span class="p">().</span><span class="n">Length</span> <span class="p">==</span> <span class="m">2</span><span class="p">)</span></div><div class='line' id='LC37'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">.</span><span class="n">MakeGenericMethod</span><span class="p">(</span><span class="n">funcType</span><span class="p">);</span></div><div class='line' id='LC38'><br/></div><div class='line' id='LC39'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">var</span> <span class="n">parameter</span> <span class="p">=</span> <span class="n">Expression</span><span class="p">.</span><span class="n">Parameter</span><span class="p">(</span><span class="n">tType</span><span class="p">);</span></div><div class='line' id='LC40'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">var</span> <span class="n">propExpress</span> <span class="p">=</span> <span class="n">Expression</span><span class="p">.</span><span class="n">Property</span><span class="p">(</span><span class="n">parameter</span><span class="p">,</span> <span class="n">prop</span><span class="p">);</span></div><div class='line' id='LC41'><br/></div><div class='line' id='LC42'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">var</span> <span class="n">sortLambda</span> <span class="p">=</span> <span class="n">lambdaBuilder</span></div><div class='line' id='LC43'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">.</span><span class="n">Invoke</span><span class="p">(</span><span class="k">null</span><span class="p">,</span> <span class="k">new</span> <span class="kt">object</span><span class="p">[]</span> <span class="p">{</span> <span class="n">propExpress</span><span class="p">,</span> <span class="k">new</span> <span class="n">ParameterExpression</span><span class="p">[]</span> <span class="p">{</span> <span class="n">parameter</span> <span class="p">}</span> <span class="p">});</span></div><div class='line' id='LC44'><br/></div><div class='line' id='LC45'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">var</span> <span class="n">sorter</span> <span class="p">=</span> <span class="k">typeof</span><span class="p">(</span><span class="n">Queryable</span><span class="p">)</span></div><div class='line' id='LC46'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">.</span><span class="n">GetMethods</span><span class="p">()</span></div><div class='line' id='LC47'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">.</span><span class="n">FirstOrDefault</span><span class="p">(</span><span class="n">x</span> <span class="p">=&gt;</span> <span class="n">x</span><span class="p">.</span><span class="n">Name</span> <span class="p">==</span> <span class="p">(</span><span class="n">isDescending</span> <span class="p">?</span> <span class="s">&quot;OrderByDescending&quot;</span> <span class="p">:</span> <span class="s">&quot;OrderBy&quot;</span><span class="p">)</span> <span class="p">&amp;&amp;</span> <span class="n">x</span><span class="p">.</span><span class="n">GetParameters</span><span class="p">().</span><span class="n">Length</span> <span class="p">==</span> <span class="m">2</span><span class="p">)</span></div><div class='line' id='LC48'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">.</span><span class="n">MakeGenericMethod</span><span class="p">(</span><span class="k">new</span><span class="p">[]</span> <span class="p">{</span> <span class="n">tType</span><span class="p">,</span> <span class="n">prop</span><span class="p">.</span><span class="n">PropertyType</span> <span class="p">});</span></div><div class='line' id='LC49'><br/></div><div class='line' id='LC50'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="p">(</span><span class="n">IQueryable</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;)</span><span class="n">sorter</span></div><div class='line' id='LC51'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">.</span><span class="n">Invoke</span><span class="p">(</span><span class="k">null</span><span class="p">,</span> <span class="k">new</span> <span class="kt">object</span><span class="p">[]</span> <span class="p">{</span> <span class="n">source</span><span class="p">,</span> <span class="n">sortLambda</span> <span class="p">});</span></div><div class='line' id='LC52'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC53'><br/></div><div class='line' id='LC54'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="n">source</span><span class="p">;</span></div><div class='line' id='LC55'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC56'><br/></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1878868/abdd14ccbfed4ca84934f51506f631f43c884ffc/gistfile1.cs" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1878868#file_gistfile1.cs" style="float:right;margin-right:10px;color:#666">gistfile1.cs</a>
            <a href="https://gist.github.com/1878868">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

]]></content:encoded>
			<wfw:commentRss>http://philsversion.com/2012/02/21/orderby-a-string-in-entity-framework/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simple Events in JavaScript</title>
		<link>http://philsversion.com/2011/10/24/simple-events-in-javascript/</link>
		<comments>http://philsversion.com/2011/10/24/simple-events-in-javascript/#comments</comments>
		<pubDate>Mon, 24 Oct 2011 14:03:51 +0000</pubDate>
		<dc:creator>Phil</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://philsversion.com/?p=275</guid>
		<description><![CDATA[A couple of weeks ago I posted about C# like Properties in JavaScript. I wanted to explore how properties could possibly be added into JavaScript, and hopefully offer some insight into how some frameworks might work. Another feature that JavaScript doesn&#8217;t explicitly support is events. Though using some of the same techniques I used for [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of weeks ago I posted about C# like <a href="http://philsversion.com/2011/09/14/properties-in-javascript/">Properties in JavaScript</a>. I wanted to explore how properties could possibly be added into JavaScript, and hopefully offer some insight into how some frameworks might work.</p>
<p>Another feature that JavaScript doesn&#8217;t explicitly support is events. Though using some of the same techniques I used for events also work very well for building events.</p>
<p>Most implementations of events in JavaScript use optional arguments in order to provide two overrides to an &#8220;event&#8221; function, one for adding a listener and the other for raising the event, like this:</p>
<pre class="brush: php">
// Add a handler
obj.click(objClicked);

function objClicked() {
}

// Raise the event
obj.click();
</pre>
<p>This provides a very straight forward to use interface (though doesn&#8217;t support unbinding.)</p>
<p>Below is a simple function for generating event functions that work in the way shown above. </p>
<p>In the returned &#8220;event&#8221; function I have no parameters, instead I check the inherent &#8220;arguments&#8221; object to see if there&#8217;s a single function parameter, and add it to &#8220;_handlers&#8221; if there is. </p>
<p>The for loop at the end raises the event by calling &#8220;apply&#8221; on the function and passing all the arguments from this method into it.</p>
<div id="gist-1309070" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="kd">var</span> <span class="nx">createEvent</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span> </div><div class='line' id='LC2'>&nbsp;&nbsp;<span class="kd">var</span> <span class="nx">_handlers</span> <span class="o">=</span> <span class="p">[];</span></div><div class='line' id='LC3'>&nbsp;&nbsp;</div><div class='line' id='LC4'>&nbsp;&nbsp;<span class="k">return</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">if</span> <span class="p">(</span><span class="nx">arguments</span><span class="p">.</span><span class="nx">length</span> <span class="o">===</span> <span class="mi">1</span> <span class="o">&amp;&amp;</span> <span class="k">typeof</span> <span class="nx">arguments</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">===</span> <span class="s1">&#39;function&#39;</span><span class="p">)</span> <span class="p">{</span></div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">_handlers</span><span class="p">.</span><span class="nx">push</span><span class="p">(</span><span class="nx">arguments</span><span class="p">[</span><span class="mi">0</span><span class="p">]);</span></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span><span class="p">;</span></div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC9'>&nbsp;&nbsp;&nbsp;&nbsp;</div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="nx">i</span> <span class="o">&lt;</span> <span class="nx">_handlers</span><span class="p">.</span><span class="nx">length</span><span class="p">;</span> <span class="o">++</span><span class="nx">i</span><span class="p">)</span> <span class="p">{</span></div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">_handlers</span><span class="p">[</span><span class="nx">i</span><span class="p">].</span><span class="nx">apply</span><span class="p">(</span><span class="k">this</span><span class="p">,</span> <span class="nx">arguments</span><span class="p">);</span></div><div class='line' id='LC12'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC13'>&nbsp;&nbsp;<span class="p">};</span> </div><div class='line' id='LC14'><span class="p">};</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1309070/8d8d7eb46f090c766b7fea4ef858325410726731/gistfile1.js" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1309070#file_gistfile1.js" style="float:right;margin-right:10px;color:#666">gistfile1.js</a>
            <a href="https://gist.github.com/1309070">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>Use like such:</p>
<pre class="brush: php">
var MyClass = new function() {
  this.click = createEvent();
}

var obj = new MyClass();

obj.click(function (x, y) {
  alert(&#039;x: &#039; + x + &#039;, y: &#039; + y);
});

obj.click(12, 24);
</pre>
]]></content:encoded>
			<wfw:commentRss>http://philsversion.com/2011/10/24/simple-events-in-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Detecting Encoding in C#</title>
		<link>http://philsversion.com/2011/09/22/detecting-encoding/</link>
		<comments>http://philsversion.com/2011/09/22/detecting-encoding/#comments</comments>
		<pubDate>Thu, 22 Sep 2011 13:38:53 +0000</pubDate>
		<dc:creator>Phil</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://philsversion.com/?p=327</guid>
		<description><![CDATA[On a project that I&#8217;ve been working on recently, I was having some trouble combining SQL scripts that where in a couple of different formats. While there&#8217;s no easy way to detect all of the possible encodings, by checking the byte order mark (BOM) there is a pretty straight forward way to detect the following [...]]]></description>
			<content:encoded><![CDATA[<p>On a project that I&#8217;ve been working on recently, I was having some trouble combining SQL scripts that where in a couple of different formats.</p>
<p>While there&#8217;s no easy way to detect all of the possible encodings, by checking the byte order mark (BOM) there is a pretty straight forward way to detect the following encodings:</p>
<ul>
<li>UTF-16</li>
<li>UTF-16BE</li>
<li>UTF-32</li>
<li>UTF-32BE</li>
<li>UTF-8</li>
</ul>
<div id="gist-1234779" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">public</span> <span class="k">static</span> <span class="n">Encoding</span> <span class="nf">GetFileEncoding</span><span class="p">(</span><span class="kt">string</span> <span class="n">path</span><span class="p">)</span></div><div class='line' id='LC2'><span class="p">{</span></div><div class='line' id='LC3'>	<span class="k">if</span> <span class="p">(</span><span class="n">path</span> <span class="p">==</span> <span class="k">null</span><span class="p">)</span></div><div class='line' id='LC4'>		<span class="k">throw</span> <span class="k">new</span> <span class="nf">ArgumentNullException</span><span class="p">(</span><span class="s">&quot;path&quot;</span><span class="p">);</span></div><div class='line' id='LC5'><br/></div><div class='line' id='LC6'>	<span class="n">var</span> <span class="n">encodings</span> <span class="p">=</span> <span class="n">Encoding</span><span class="p">.</span><span class="n">GetEncodings</span><span class="p">()</span></div><div class='line' id='LC7'>		<span class="p">.</span><span class="n">Select</span><span class="p">(</span><span class="n">e</span> <span class="p">=&gt;</span> <span class="n">e</span><span class="p">.</span><span class="n">GetEncoding</span><span class="p">())</span></div><div class='line' id='LC8'>		<span class="p">.</span><span class="n">Select</span><span class="p">(</span><span class="n">e</span> <span class="p">=&gt;</span> <span class="k">new</span> <span class="p">{</span> <span class="n">Encoding</span> <span class="p">=</span> <span class="n">e</span><span class="p">,</span> <span class="n">Preamble</span> <span class="p">=</span> <span class="n">e</span><span class="p">.</span><span class="n">GetPreamble</span><span class="p">()</span> <span class="p">})</span></div><div class='line' id='LC9'>		<span class="p">.</span><span class="n">Where</span><span class="p">(</span><span class="n">e</span> <span class="p">=&gt;</span> <span class="n">e</span><span class="p">.</span><span class="n">Preamble</span><span class="p">.</span><span class="n">Any</span><span class="p">())</span></div><div class='line' id='LC10'>		<span class="p">.</span><span class="n">ToArray</span><span class="p">();</span></div><div class='line' id='LC11'><br/></div><div class='line' id='LC12'>	<span class="n">var</span> <span class="n">maxPrembleLength</span> <span class="p">=</span> <span class="n">encodings</span><span class="p">.</span><span class="n">Max</span><span class="p">(</span><span class="n">e</span> <span class="p">=&gt;</span> <span class="n">e</span><span class="p">.</span><span class="n">Preamble</span><span class="p">.</span><span class="n">Length</span><span class="p">);</span></div><div class='line' id='LC13'>	<span class="kt">byte</span><span class="p">[]</span> <span class="n">buffer</span> <span class="p">=</span> <span class="k">new</span> <span class="kt">byte</span><span class="p">[</span><span class="n">maxPrembleLength</span><span class="p">];</span></div><div class='line' id='LC14'><br/></div><div class='line' id='LC15'>	<span class="k">using</span> <span class="p">(</span><span class="n">var</span> <span class="n">stream</span> <span class="p">=</span> <span class="n">File</span><span class="p">.</span><span class="n">OpenRead</span><span class="p">(</span><span class="n">path</span><span class="p">))</span></div><div class='line' id='LC16'>	<span class="p">{</span></div><div class='line' id='LC17'>		<span class="n">stream</span><span class="p">.</span><span class="n">Read</span><span class="p">(</span><span class="n">buffer</span><span class="p">,</span> <span class="m">0</span><span class="p">,</span> <span class="p">(</span><span class="kt">int</span><span class="p">)</span><span class="n">Math</span><span class="p">.</span><span class="n">Min</span><span class="p">(</span><span class="n">maxPrembleLength</span><span class="p">,</span> <span class="n">stream</span><span class="p">.</span><span class="n">Length</span><span class="p">));</span></div><div class='line' id='LC18'>	<span class="p">}</span></div><div class='line' id='LC19'><br/></div><div class='line' id='LC20'>	<span class="k">return</span> <span class="n">encodings</span></div><div class='line' id='LC21'>		<span class="p">.</span><span class="n">Where</span><span class="p">(</span><span class="n">enc</span> <span class="p">=&gt;</span> <span class="n">enc</span><span class="p">.</span><span class="n">Preamble</span><span class="p">.</span><span class="n">SequenceEqual</span><span class="p">(</span><span class="n">buffer</span><span class="p">.</span><span class="n">Take</span><span class="p">(</span><span class="n">enc</span><span class="p">.</span><span class="n">Preamble</span><span class="p">.</span><span class="n">Length</span><span class="p">)))</span></div><div class='line' id='LC22'>		<span class="p">.</span><span class="n">Select</span><span class="p">(</span><span class="n">enc</span> <span class="p">=&gt;</span> <span class="n">enc</span><span class="p">.</span><span class="n">Encoding</span><span class="p">)</span></div><div class='line' id='LC23'>		<span class="p">.</span><span class="n">FirstOrDefault</span><span class="p">()</span> <span class="p">??</span> <span class="n">Encoding</span><span class="p">.</span><span class="n">Default</span><span class="p">;</span></div><div class='line' id='LC24'><span class="p">}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1234779/78f49981c4d2e2465612555f7b0a1a979c78af31/gistfile1.cs" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1234779#file_gistfile1.cs" style="float:right;margin-right:10px;color:#666">gistfile1.cs</a>
            <a href="https://gist.github.com/1234779">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

]]></content:encoded>
			<wfw:commentRss>http://philsversion.com/2011/09/22/detecting-encoding/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Properties in JavaScript</title>
		<link>http://philsversion.com/2011/09/14/properties-in-javascript/</link>
		<comments>http://philsversion.com/2011/09/14/properties-in-javascript/#comments</comments>
		<pubDate>Wed, 14 Sep 2011 10:53:20 +0000</pubDate>
		<dc:creator>Phil</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://philsversion.com/?p=272</guid>
		<description><![CDATA[JavaScript doesn&#8217;t inherently support properties in the same way that .net languages do, which is a shame since the syntax really helps simplify access internalized data in a structured way. There&#8217;s a common solution to this in JavaScript, that exploits the fact that JavaScript function arguments are optional. A property function will have a single [...]]]></description>
			<content:encoded><![CDATA[<p>JavaScript doesn&#8217;t inherently support properties in the same way that .net languages do, which is a shame since the syntax really helps simplify access internalized data in a structured way.</p>
<p>There&#8217;s a common solution to this in JavaScript, that exploits the fact that JavaScript function arguments are optional. A property function will have a single argument. If the argument is <em>undefined</em> then the current call is a &#8216;get&#8217;, otherwise it&#8217;s a &#8216;set&#8217;. jQuery has many good examples of this, for example the <em>val()</em> method:</p>
<div style="margin: 0 0 2em 2em"><code><strong>var</strong> value <strong>=</strong> $('input').val(); // Getter<br />
$('input').val(123); // Setter</p>
<p></code></div>
<p>It isn&#8217;t particularly hard to define a method this way, below is an example class with a single property, &#8216;name&#8217;:</p>
<div style="margin: 0 0 2em 2em"><code>
<pre>// A new class
<strong>var</strong> MyClass <strong>=</strong> <strong>function</strong>() {
    <strong>var</strong> _name;

    <strong>this</strong>.name <strong>=</strong> <strong>function</strong>(value) {
        <strong>if</strong> (value <strong>!==</strong> <strong>undefined</strong>)
            _name <strong>=</strong> value;

        <strong>return</strong> _name;
    };
};

// Example usage
<strong>var</strong> instance <strong>=</strong> <strong>new</strong> MyClass();
instance.name('Phil');
<strong>var</strong> name <strong>=</strong> instance.name(); // name = 'Phil'
</pre>
<p></code></div>
<p>This way of doing things is achieves the desired effect, but ends up being overly verbose if you have a lot of properties that are just wrappers around a value, like an auto-implemented property is in C#.</p>
<p>I came up with the solution below while I was working on <a href="http://findthatrobot.com" target="_blank">findthatrobot.com</a>. It helps in the creation of auto-implemented like properties, as well as allowing the getter and setter to be customized, or just one of the two, creating a read-only or write-only property.</p>
<p>With this function a property can be created as such:</p>
<div style="margin: 0 0 2em 2em"><code>
<pre><strong>var</strong> MyClass <strong>=</strong> <strong>function</strong>() {
    <strong>var</strong> customPropertyValue;

    // Auto-implemented proeprty
    <strong>this</strong>.prop1 <strong>=</strong> createProperty();

    // Custom getter and setter
    <strong>this</strong>.prop2 <strong>=</strong> createProperty({
        get: <strong>function</strong>() { <strong>return</strong> customPropertyValue; },
        set: <strong>function</strong>(value) { customPropertyValue <strong>=</strong> value; }
    });
};
</pre>
<p></code></div>
<p>And here is the &#8216;createProperty&#8217; function:</p>
<div id="gist-1216184" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="kd">var</span> <span class="nx">createProperty</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">getSet</span><span class="p">)</span> <span class="p">{</span> </div><div class='line' id='LC2'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">var</span> <span class="nx">_value</span><span class="p">;</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">var</span> <span class="nx">autoImplement</span> <span class="o">=</span> <span class="p">{</span></div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">get</span><span class="o">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span> <span class="k">return</span> <span class="nx">_value</span><span class="p">;</span> <span class="p">},</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">set</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">value</span><span class="p">)</span> <span class="p">{</span> <span class="nx">_value</span> <span class="o">=</span> <span class="nx">value</span><span class="p">;</span> <span class="k">return</span> <span class="nx">_value</span><span class="p">;</span> <span class="p">}</span></div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">};</span></div><div class='line' id='LC7'><br/></div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">getSet</span> <span class="o">=</span> <span class="nx">getSet</span> <span class="o">||</span> <span class="nx">autoImplement</span><span class="p">;</span></div><div class='line' id='LC9'><br/></div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">var</span> <span class="nx">get</span> <span class="o">=</span> <span class="nx">getSet</span><span class="p">.</span><span class="nx">get</span> <span class="o">||</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span> <span class="k">throw</span> <span class="k">new</span> <span class="nb">Error</span><span class="p">(</span><span class="s1">&#39;No get method defined for this property.&#39;</span><span class="p">);</span> <span class="p">},</span></div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">set</span> <span class="o">=</span> <span class="nx">getSet</span><span class="p">.</span><span class="nx">set</span> <span class="o">||</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span> <span class="k">throw</span> <span class="k">new</span> <span class="nb">Error</span><span class="p">(</span><span class="s1">&#39;No set method defined for this property.&#39;</span><span class="p">);</span> <span class="p">};</span></div><div class='line' id='LC12'><br/></div><div class='line' id='LC13'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="kd">function</span><span class="p">(</span><span class="nx">value</span><span class="p">)</span> <span class="p">{</span></div><div class='line' id='LC14'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">if</span> <span class="p">(</span><span class="nx">value</span> <span class="o">!==</span> <span class="kc">undefined</span><span class="p">)</span></div><div class='line' id='LC15'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="nx">set</span><span class="p">(</span><span class="nx">value</span><span class="p">);</span></div><div class='line' id='LC16'><br/></div><div class='line' id='LC17'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="nx">get</span><span class="p">();</span></div><div class='line' id='LC18'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">};</span> </div><div class='line' id='LC19'><span class="p">};</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1216184/961b31f00f1cb5dc1b92a30676861472a082c141/gistfile1.js" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1216184#file_gistfile1.js" style="float:right;margin-right:10px;color:#666">gistfile1.js</a>
            <a href="https://gist.github.com/1216184">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>Phil</p>
]]></content:encoded>
			<wfw:commentRss>http://philsversion.com/2011/09/14/properties-in-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Async Entity Framework Queries</title>
		<link>http://philsversion.com/2011/09/07/async-entity-framework-queries/</link>
		<comments>http://philsversion.com/2011/09/07/async-entity-framework-queries/#comments</comments>
		<pubDate>Wed, 07 Sep 2011 09:27:28 +0000</pubDate>
		<dc:creator>Phil</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Async CTP]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://philsversion.com/?p=268</guid>
		<description><![CDATA[I&#8217;ve been writing a lot of Node.js recently, and I&#8217;ve really love how the asynchronous database access works, and thought to myself &#8220;I wonder if I can do that with Entity Framework?&#8221; While I couldn&#8217;t find anywhere in EF the inherently support any form of async calls, I did find that you can with the [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been writing a <a href="http://philsversion.com/2011/08/24/lessons-learnt-from-my-first-node-js-project/" title="Lessons learnt from my first Node.js project" target="_blank">lot of Node.js recently</a>, and I&#8217;ve really love how the asynchronous database access works, and thought to myself &#8220;I wonder if I can do that with Entity Framework?&#8221;</p>
<p>While I couldn&#8217;t find anywhere in EF the inherently support any form of async calls, I did find that you can with the underlying SqlConnection (assuming you&#8217;re using MSSQL.)</p>
<p>So with a little bit of <a href="http://msdn.microsoft.com/en-us/vstudio/gg316360" title="Visual Studio Asynchronous Programming" target="_blank">Async CTP</a> magic mixed in, I created an extension method to read the data asynchronously.</p>
<p><script src="https://gist.github.com/1200123.js?file=gistfile1.cs"></script></p>
<p>Unfortunately I couldn&#8217;t find an obvious way to open the connection or write data asynchronously, but I think this is good step.</p>
<p>Phil</p>
]]></content:encoded>
			<wfw:commentRss>http://philsversion.com/2011/09/07/async-entity-framework-queries/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Find That Robot on GitHub</title>
		<link>http://philsversion.com/2011/09/01/find-that-robot-on-github/</link>
		<comments>http://philsversion.com/2011/09/01/find-that-robot-on-github/#comments</comments>
		<pubDate>Thu, 01 Sep 2011 17:47:37 +0000</pubDate>
		<dc:creator>Phil</dc:creator>
				<category><![CDATA[Node.js]]></category>

		<guid isPermaLink="false">http://philsversion.com/?p=260</guid>
		<description><![CDATA[For better or worse Find That Robot&#8216;s source code is now on GitHub. Comments and questions are welcome. Phil]]></description>
			<content:encoded><![CDATA[<p>For better or worse <a href="http://findthatrobot.com" target="_blank">Find That Robot</a>&#8216;s source code is now on <a href="http://github.com/neoGeneva/findthatrobot" target="_blank">GitHub</a>.</p>
<p>Comments and questions are welcome.</p>
<p>Phil</p>
]]></content:encoded>
			<wfw:commentRss>http://philsversion.com/2011/09/01/find-that-robot-on-github/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Lessons learnt from my first Node.js project</title>
		<link>http://philsversion.com/2011/08/24/lessons-learnt-from-my-first-node-js-project/</link>
		<comments>http://philsversion.com/2011/08/24/lessons-learnt-from-my-first-node-js-project/#comments</comments>
		<pubDate>Wed, 24 Aug 2011 12:08:27 +0000</pubDate>
		<dc:creator>Phil</dc:creator>
				<category><![CDATA[Node.js]]></category>

		<guid isPermaLink="false">http://philsversion.com/?p=217</guid>
		<description><![CDATA[Over the last couple of months my wife and I have been working on a little web game called findthatrobot.com. It&#8217;s a small, building it for the fun of it project, and gave me a chance to stretch my newly acquired Node.js muscle. I&#8217;ve played around with some small Node.js projects over the last year or so, mostly [...]]]></description>
			<content:encoded><![CDATA[<p>Over the last couple of months <a href="http://www.tonibarrett.com/">my wife</a> and I have been working on a little web game called <a href="http://findthatrobot.com">findthatrobot.com</a>. It&#8217;s a small, building it for the fun of it project, and gave me a chance to stretch my newly acquired <a href="http://nodejs.org/">Node.js</a> muscle.</p>
<p>I&#8217;ve played around with some small Node.js projects over the last year or so, mostly following tutorials and the such, and this was my first complete project. I&#8217;m going to share with you what worked for me and what didn&#8217;t, in hopes that anyone else out there might learn something to make their lives easier, or perhaps be inspired to try Node.js for the first time.</p>
<p>&nbsp;</p>
<p><span id="more-217"></span></p>
<h2>Getting Started and Development Environment</h2>
<p>The first thing I needed to get set up was the development environment. We&#8217;d already decided on using a free<a href="http://aws.amazon.com/ec2/"> Amazon EC2</a> Micro instance as our hosting, and I&#8217;d played around with running <a href="http://c9.io/">Cloud9 IDE</a> locally on a Virtual Box running Ubuntu, so setting up Cloud9 IDE on EC2 seemed like the most sensible first step forward.  For those who don&#8217;t know, Cloud9 IDE is a browser based IDE, which might seem strange at first, though it doesn&#8217;t take long to see what a powerful tool it is, and how much of a pleasure it is to use. I really can&#8217;t recommend Cloud9 IDE enough.</p>
<p>In the end I set up two instances listening on different ports, since the Cloud9IDE in NPM is a limit version of what&#8217;s on c9.io, and restricted it to one user at a time. I used GIT to sync the changes between the two, and to deploy to the production site and backup locally.</p>
<p>&nbsp;</p>
<h2>Frameworks and Middleware</h2>
<p>When I started, I didn&#8217;t have much of an idea of what the final structure of the app would be. I&#8217;ve had a fair bit of experience in building MVC web apps, so I figured that&#8217;d be a good place to start.</p>
<p>After trying a couple of different frameworks and doing a bit of research on what was popular, I discovered <a href="http://expressjs.com/">Express</a>, which takes <a href="http://senchalabs.github.com/connect/">Connect</a>, a middleware framework, and expands it into a reasonably complete web app framework. I come from an ASP.net background, so the word &#8220;middleware&#8221; didn&#8217;t mean a lot to me a first. Simply put, a middleware component is a function that acts on request and / or response. Connect &#8220;connects&#8221; these functions in a pipeline. An example middleware component might be parsing a file in the request, or compressing a response.</p>
<p>It took me a while to pick the bits and pieces of middleware I needed, though most of what I wanted came built in to Express or Connect. I used a couple of components built by others, and built a few myself. I found it really easy to create my own, perhaps too easy, and got carried away re-inventing the wheel a couple of times, though it was all good learning.</p>
<p>Here&#8217;s the additional bits of middleware I used:</p>
<ul>
<li>A custom logger for errors and request logging. I loved the inbuilt formatting options in Connect.logger, but I wanted to output the data into a rolling log. I found <a href="https://github.com/indexzero/winston">Winston</a> was good for the job, as well as giving me more logging capabilities elsewhere. Winston wasn&#8217;t connect ready to begin with, though it didn&#8217;t take much coaxing to make the Connect.logger use it as its output.</li>
<li>I had quite a bit of trouble finding a gzip component. I started with <a href="https://github.com/nateps/connect-gzip">connect-gzip</a> but the static encoding didn&#8217;t add an expires header. I switched to <a href="https://github.com/tomgallacher/gzippo">gzippo</a> which did, but didn&#8217;t have compression for dynamic files. So I ended up using both. I&#8217;m not entirely sure of how well either component performs, but they both seemed to work well enough for my purposes.</li>
<li>I added <a href="https://github.com/visionmedia/connect-form">connect-form</a> to deal with uploading files in the admin screens.</li>
<li>I wrote some custom tracing code that utilized Winston&#8217;s tracing capabilities and the inbuilt connect profiler. It also added custom timing logic to to each middleware component. After writing all this profiling logic, the only thing I discovered was that everything was running well.</li>
</ul>
<p>&nbsp;</p>
<h2>Coding Style and Standards</h2>
<p>There&#8217;s a couple of practices that I picked up early on, most of which I learnt from Stella Laurenzo&#8217;s post on <a href="http://stella.laurenzo.org/2011/03/bulletproof-node-js-coding/">Bulletproof Node.js Coding</a>.</p>
<p>The habit of returning on the last statement is a technique I think every Node.js coder should use. The code becomes much easier to follow since callbacks often obscure the end of the function, and it stops you accidentally executing code after a call to an async function.</p>
<p>Using named function declarations instead of inline functions vastly improves maintainability. It makes following the flow of async callbacks much more straight forward to read, and makes the code a little more self-documenting with the callbacks given names.</p>
<p>Data access was something I struggled with and I think, given time, I would have rewritten much of my current solution. I used <a href="http://redis.io/">redis</a> as my sole data store because I was more concerned with performance than data reliability. This meant that the act of reading and writing data was simply serializing and deserializing JSON strings to and from redis. I kept a set of model objects which I serialized directly into JSON, and each model object had an &#8216;update&#8217; method that took the deserialized data and copied it into the instance. The goal of this was to make sure the fields on the object where always consistent, and gave the opportunity to deal with different versions of the data.</p>
<p>I think the approach was generally okay, but in its current state there&#8217;s a lot of duplication. If I were to rewrite it, I&#8217;d attempt to abstract much of the serializing, deserializing and object update logic. I&#8217;d also attempt to centralize the actual calls to redis, as at the moment there&#8217;s a lot of code that&#8217;d need to change if I wanted to change data providers.</p>
<p>The last thing I&#8217;d like to mention is using a Block to centralize error handling, as mentioned Stella Laurenzo&#8217;s blog post. This pattern fits very nicely into the Express framework and can be a lifesaver, because any exception that bubbles up to the core Node.js event loop will terminate your Node.js instance. The code in Express itself already has error handling built in, but if a callback comes from somewhere else (such as redis) the exception will cause problems. The Block pattern simplifies the error handling, reducing the amount of code you need to write. This sort of error handling is a requirement for any Node.js app.</p>
<p>&nbsp;</p>
<h2>Final Thoughts</h2>
<p>If you&#8217;re coming from a Windows / .NET development background there&#8217;s a steep, but short, learning curve to start programming in Node.js, but it&#8217;s well worth it. JavaScript offers a very different way to thinking about application programming from C# and VB.net, it feels more free-form and dynamic and gives you more of an opportunity mould your application into a shape that you feel comfortable with.</p>
<p>Node.js is still a very new environment, tools are still being built, patterns and best practices are being forged, much will change in times to come and it all makes Node.js a fun tool to work with. It has great potential as a tool for building websites and so much more, and I hope that you get a chance to use it on your next project.</p>
<p>&nbsp;</p>
<p>// Phil</p>
]]></content:encoded>
			<wfw:commentRss>http://philsversion.com/2011/08/24/lessons-learnt-from-my-first-node-js-project/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Red-Black Tree in F#</title>
		<link>http://philsversion.com/2011/06/30/red-black-tree-in-f/</link>
		<comments>http://philsversion.com/2011/06/30/red-black-tree-in-f/#comments</comments>
		<pubDate>Thu, 30 Jun 2011 12:40:21 +0000</pubDate>
		<dc:creator>Phil</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.philsversion.com/?p=206</guid>
		<description><![CDATA[Here&#8217;s some F# just for fun, it&#8217;s some code translated from the Qi code here.]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s some F# just for fun, it&#8217;s some code translated from the <a href="http://jng.imagine27.com/articles/2011-06-28-141124_purely_functional_types_red_black_trees_in_qi.html">Qi code here</a>.</p>
<p><script src="https://gist.github.com/1056026.js?file=RedBlackTree.fsx"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://philsversion.com/2011/06/30/red-black-tree-in-f/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Alternating Row Styles in Silverlight</title>
		<link>http://philsversion.com/2010/11/22/alternating-row-styles-in-silverlight/</link>
		<comments>http://philsversion.com/2010/11/22/alternating-row-styles-in-silverlight/#comments</comments>
		<pubDate>Sun, 21 Nov 2010 20:19:33 +0000</pubDate>
		<dc:creator>Phil</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://www.philsversion.com/?p=194</guid>
		<description><![CDATA[Update: There was an issue when using ItemsControl because of the way I was determining if one control was in another (I was using the DataContext.) This example code and attached ZIP have been updated. Because the ItemsControl in Silverlight 4 doesn&#8217;t support alternating styles on the child items, I&#8217;ve made this set of attached [...]]]></description>
			<content:encoded><![CDATA[<p>Update: There was an issue when using ItemsControl because of the way I was determining if one control was in another (I was using the DataContext.) This example code and attached ZIP have been updated.</p>
<p>Because the ItemsControl in Silverlight 4 doesn&#8217;t support alternating styles on the child items, I&#8217;ve made this set of attached properties to allow you to switch the style on any item contained within an ItemsControl or anything that inherits from it (e.g. ListBox.)</p>
<p>I&#8217;ve uploaded a sample project, but here&#8217;s the entirety of the code for those who don&#8217;t want to download anything.</p>
<p><a href="http://philsversion.com.s109722.gridserver.com/wp-content/uploads/2011/01/SilverlightApplication1.zip">SilverlightApplication1.zip</a></p>
<p>Here&#8217;s a sample of it&#8217;s usage:</p>
<pre class="brush: xml">
&lt;UserControl x:Class=&quot;SilverlightApplication1.MainPage&quot;
    xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
    xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;
    xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
    xmlns:local=&quot;clr-namespace:SilverlightApplication1&quot;
    mc:Ignorable=&quot;d&quot; Loaded=&quot;UserControl_Loaded&quot;
    d:DesignHeight=&quot;300&quot; d:DesignWidth=&quot;400&quot;&gt;

    &lt;Grid x:Name=&quot;LayoutRoot&quot; Background=&quot;White&quot;&gt;
        &lt;ListBox x:Name=&quot;ListItems&quot;&gt;
            &lt;ListBox.ItemTemplate&gt;
                &lt;DataTemplate&gt;
                    &lt;Border&gt;
                        &lt;Border.Style&gt;
                            &lt;Style TargetType=&quot;Border&quot;&gt;
                                &lt;Setter Property=&quot;Background&quot; Value=&quot;White&quot; /&gt;
                            &lt;/Style&gt;
                        &lt;/Border.Style&gt;
                        &lt;local:ItemsControlAlternation.AlternateStyle&gt;
                            &lt;Style TargetType=&quot;Border&quot;&gt;
                                &lt;Setter Property=&quot;Background&quot; Value=&quot;LightBlue&quot; /&gt;
                            &lt;/Style&gt;
                        &lt;/local:ItemsControlAlternation.AlternateStyle&gt;
                        &lt;ContentPresenter Content=&quot;{Binding}&quot; /&gt;
                    &lt;/Border&gt;
                &lt;/DataTemplate&gt;
            &lt;/ListBox.ItemTemplate&gt;
        &lt;/ListBox&gt;
    &lt;/Grid&gt;

&lt;/UserControl&gt;
</pre>
<p>And here&#8217;s the main part of the code, separated into two classes. One for the attached properties, and one that&#8217;s the new behavior. Also I&#8217;ve included two extension methods in this example, that aren&#8217;t specific to this code, but do make it cleaner.</p>
<pre class="brush: c#">
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace SilverlightApplication1
{
    public static class ItemsControlAlternation
    {
        public static readonly DependencyProperty AlternateStyleProperty =
            DependencyProperty.RegisterAttached(&quot;AlternateStyle&quot;, typeof(Style), typeof(ItemsControlAlternation), new PropertyMetadata(AlternateStylePropertySet));

        public static readonly DependencyProperty AlternationIndexProperty =
            DependencyProperty.RegisterAttached(&quot;AlternationIndex&quot;, typeof(int), typeof(ItemsControlAlternation), new PropertyMetadata(2, AlternationIndexPropertySet));

        private static readonly DependencyProperty AlternationHelperProperty =
            DependencyProperty.RegisterAttached(&quot;AlternationHelper&quot;, typeof(ItemsControlAlternationHelper), typeof(ItemsControlAlternation), new PropertyMetadata(null));

        public static Style GetAlternateStyle(DependencyObject obj)
        {
            return (Style)obj.GetValue(AlternateStyleProperty);
        }

        public static void SetAlternateStyle(DependencyObject obj, Style value)
        {
            obj.SetValue(AlternateStyleProperty, value);
        }

        public static int GetAlternationIndex(DependencyObject obj)
        {
            return (int)obj.GetValue(AlternationIndexProperty);
        }

        public static void SetAlternationIndex(DependencyObject obj, int value)
        {
            obj.SetValue(AlternationIndexProperty, value);
        }

        private static ItemsControlAlternationHelper GetAlternationHelper(DependencyObject obj)
        {
            return (ItemsControlAlternationHelper)obj.GetValue(AlternationHelperProperty);
        }

        private static void SetAlternationHelper(DependencyObject obj, ItemsControlAlternationHelper value)
        {
            obj.SetValue(AlternationHelperProperty, value);
        }

        private static void AlternateStylePropertySet(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            ItemsControlAlternationHelper helper = GetOrCreateAlternationHelper(sender);

            helper.AlternateStyle = (Style)e.NewValue;
        }

        private static void AlternationIndexPropertySet(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            ItemsControlAlternationHelper helper = GetOrCreateAlternationHelper(sender);

            helper.AlternationIndex = (int)e.NewValue;
        }

        private static ItemsControlAlternationHelper GetOrCreateAlternationHelper(DependencyObject target)
        {
            ItemsControlAlternationHelper helper = GetAlternationHelper(target);

            if (helper == null)
            {
                helper = new ItemsControlAlternationHelper(target as FrameworkElement);
                SetAlternationHelper(target, helper);
            }

            return helper;
        }
    }

    internal class ItemsControlAlternationHelper
    {
        private FrameworkElement targetItem;
        private Style originalStyle;
        private Style alternateStyle;
        private int alternationIndex;

        private ItemsControl parentCollection;
        private INotifyCollectionChanged parentCollectionItems;
        private FrameworkElement[] parentPath;

        public ItemsControlAlternationHelper(FrameworkElement targetItem)
        {
            if (targetItem == null)
            {
                throw new ArgumentNullException(&quot;targetItem&quot;, &quot;targetItem is null.&quot;);
            }

            this.targetItem = targetItem;
            this.originalStyle = targetItem.Style;
            this.alternationIndex = 2;

            // Check for loaded in case the element hasn&#039;t been added to the visual tree yet.
            targetItem.Loaded += TargetItemLoaded;

            LocateParents();
        }

        /// &lt;summary&gt;
        /// The style to apply to the alternate items.
        /// &lt;/summary&gt;
        public Style AlternateStyle
        {
            get { return alternateStyle; }
            set
            {
                alternateStyle = value;
                UpdateAlernationStyle();
            }
        }

        /// &lt;summary&gt;
        /// At what frequency to apply the alternate style. Defaults to 2, which applies the style to every second item.
        /// &lt;/summary&gt;
        public int AlternationIndex
        {
            get { return alternationIndex; }
            set
            {
                if (value == 0)
                {
                    throw new ArgumentOutOfRangeException(&quot;value&quot;, &quot;value must be non-zero.&quot;);
                }

                alternationIndex = value;
                UpdateAlernationStyle();
            }
        }

        /// &lt;summary&gt;
        /// Parses the visual tree of the target element to find the ItemsControl
        /// &lt;/summary&gt;
        private void LocateParents()
        {
            if (parentCollectionItems != null)
            {
                parentCollectionItems.CollectionChanged -= ParentCollectionChanged;
            }

            DependencyObject[] parents = targetItem.GetVisualParents().ToArray();

            parentCollection = parents.OfType&lt;ItemsControl&gt;().FirstOrDefault();

            if (parentCollection == null)
            {
                return;
            }

            parentPath = parents.TakeWhile(x =&gt; x != parentCollection).Skip(1).OfType&lt;FrameworkElement&gt;().ToArray();
            parentCollectionItems = parentCollection.Items as INotifyCollectionChanged;

            if (parentCollectionItems != null)
            {
                parentCollectionItems.CollectionChanged += ParentCollectionChanged;
            }
        }

        private void TargetItemLoaded(object sender, RoutedEventArgs e)
        {
            LocateParents();
            UpdateAlernationStyle();
        }

        private void ParentCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            UpdateAlernationStyle();
        }

        /// &lt;summary&gt;
        /// Update the Style of the target element.
        /// &lt;/summary&gt;
        private void UpdateAlernationStyle()
        {
            if (IsAlternate())
            {
                targetItem.Style = AlternateStyle;
            }
            else
            {
                targetItem.Style = originalStyle;
            }
        }

        /// &lt;summary&gt;
        /// Checks to see if the item is at the alternate index
        /// &lt;/summary&gt;
        private bool IsAlternate()
        {
            if (parentCollection == null)
            {
                return false;
            }

            Panel panel = parentCollection.GetVisualChildrenRecursive().OfType&lt;Panel&gt;().FirstOrDefault();

            if (panel == null)
                return false;

            int itemIndex = panel.Children.IndexOf(i =&gt; i.GetVisualChildrenRecursive().Contains(targetItem));

            return (itemIndex + 1) % AlternationIndex == 0;
        }

    }

    public static class Extensions
    {
        /// &lt;summary&gt;
        /// Walks the visual tree to find all of an items parents.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; GetVisualParents(this DependencyObject source)
        {
            if (source == null)
            {
                throw new ArgumentNullException(&quot;source&quot;, &quot;source is null.&quot;);
            }

            DependencyObject parent = VisualTreeHelper.GetParent(source);

            while (parent != null)
            {
                yield return parent;

                parent = VisualTreeHelper.GetParent(parent);
            }
        }

        /// &lt;summary&gt;
        /// Returns the first index of an item in the collection that matches the given predicate.
        /// &lt;/summary&gt;
        public static int IndexOf&lt;T&gt;(this IEnumerable&lt;T&gt; source, Func&lt;T, bool&gt; predicate)
        {
            return source
                .Select((item, index) =&gt; new { item, index })
                .Where(i =&gt; predicate(i.item))
                .Select(i =&gt; i.index + 1)
                .FirstOrDefault() - 1;
        }

        /// &lt;summary&gt;
        /// Returns all the direct visual children of an object
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; GetVisualChildren(this DependencyObject source)
        {
            return Enumerable.Range(0, VisualTreeHelper.GetChildrenCount(source))
                .Select(i =&gt; VisualTreeHelper.GetChild(source, i));
        }

        /// &lt;summary&gt;
        /// Returns the children of a dependancy object using a breadth first algorithm
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; GetVisualChildrenRecursive(this DependencyObject source)
        {
            DependencyObject[] children = source.GetVisualChildren()
                .ToArray();

            while (children.Any())
            {
                foreach (var item in children)
                {
                    yield return item;
                }

                children = children.SelectMany(c =&gt; c.GetVisualChildren())
                    .ToArray();
            }
        }
    }
}
</pre>
<p>I&#8217;m not particularly happy with how it uses DataContext to determine if it&#8217;s a sub-item, so any suggestions on how to improve it would be appreciated <img src='http://philsversion.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Phil</p>
]]></content:encoded>
			<wfw:commentRss>http://philsversion.com/2010/11/22/alternating-row-styles-in-silverlight/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Dealing with infinite recursion redux</title>
		<link>http://philsversion.com/2010/06/18/dealing-with-infinite-recursion-redux/</link>
		<comments>http://philsversion.com/2010/06/18/dealing-with-infinite-recursion-redux/#comments</comments>
		<pubDate>Thu, 17 Jun 2010 19:02:00 +0000</pubDate>
		<dc:creator>Phil</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[.NET Examples]]></category>
		<category><![CDATA[Infinite Recursion]]></category>
		<category><![CDATA[StackOverFlowException]]></category>
		<category><![CDATA[Threading]]></category>
		<category><![CDATA[ThreadStaticAttrbibute]]></category>

		<guid isPermaLink="false">http://www.philsversion.com/?p=182</guid>
		<description><![CDATA[In a previous post about infinite recursion I proposed the use of the ThreadStaticAttribute to deal with infinite recursion. This approach is fine so long as your recursion doesn&#8217;t cross threads, if it does the static variable will be reset for each new thread and offer not benefit. Here&#8217;s an example, in .NET 4.0, to [...]]]></description>
			<content:encoded><![CDATA[<p>In a <a href="/2009/04/01/dealing-with-infinite-recursion/">previous post about infinite recursion</a> I proposed the use of the <a href="http://msdn.microsoft.com/en-us/library/system.threadstaticattribute.aspx" target="_blank">ThreadStaticAttribute</a> to deal with infinite recursion. This approach is fine so long as your recursion doesn&#8217;t cross threads, if it does the static variable will be reset for each new thread and offer not benefit.</p>
<p>Here&#8217;s an example, in .NET 4.0, to show you what I mean. In this example I have a simple logging setup, with a list of IListeners which handle messages that a logged with the LogMessage function. It&#8217;ll get into a infinite recursive loop becuase the LogToDiskListener attempts to log a message, and the ThreadStaticAttribute doesn&#8217;t help because each listener is executed in it&#8217;s own thread.</p>
<pre class="brush: csharp">
        [ThreadStatic]
        private static bool _isLoggingMessage;

        private static List&lt;IListener&gt; _listeners = new List&lt;IListener&gt;();

        public static void Main()
        {
            _listeners.Add(new LogToDiskListener());
            LogMessage(&quot;Starting main function&quot;);
        }

        private static void LogMessage(string message)
        {
            if (_isLoggingMessage)
                return;

            _isLoggingMessage = true;

            _listeners.AsParallel()
                .ForAll(listener =&gt; listener.HandleMessage(message));

            _isLoggingMessage = false;
        }

        public class LogToDiskListener : IListener
        {
            public void HandleMessage(string message)
            {
                LogMessage(&quot;Writing message to disk&quot;);

                // Write the message to disk
            }
        }

        public interface IListener
        {
            void HandleMessage(string message);
        }
</pre>
<p>The code above won&#8217;t throw a StackOverFlowException, but will continue to use CPU and increase memory usage until it starves itself of threads.</p>
<p>Fortunately there is a particular solution to this scenario, using the <a href="http://msdn.microsoft.com/en-us/library/system.runtime.remoting.messaging.callcontext.logicalsetdata.aspx" target="_blank">CallContext.LogicalSetData</a> method. Any data set with this method will continue to flow down through child threads, offering a solution to the recursion. Below is a example that wont loop indefinitely:</p>
<pre class="brush: csharp">
        private const string IsLoggingMessageKey = &quot;LoggingExample_IsLoggingMessage&quot;;

        private static bool IsLoggingMessage
        {
            get
            {
                return ((bool?)CallContext.LogicalGetData(IsLoggingMessageKey))
                    .GetValueOrDefault();
            }
            set
            {
                CallContext.LogicalSetData(IsLoggingMessageKey, value);
            }
        }

        private static List&lt;IListener&gt; _listeners = new List&lt;IListener&gt;();

        public static void Main()
        {
            _listeners.Add(new LogToDiskListener());
            LogMessage(&quot;Starting main function&quot;);
        }

        private static void LogMessage(string message)
        {
            if (IsLoggingMessage)
                return;

            _listeners.AsParallel()
                .ForAll(listener =&gt;
                {
                    IsLoggingMessage = true;
                    listener.HandleMessage(message);
                });
        }

        public class LogToDiskListener : IListener
        {
            public void HandleMessage(string message)
            {
                LogMessage(&quot;Writing message to disk&quot;);

                // Write the message to disk
            }
        }

        public interface IListener
        {
            void HandleMessage(string message);
        }
</pre>
<p>In the new version of the I&#8217;ve replaced the field with a ThreadStaticAttribue with a property that wraps around some calls to the CallContext. I&#8217;ve also removed the call to set it to false, since it&#8217;s value is lost as soon as all the threads that are using are finished. I&#8217;ve also move the place where the new property is set to within the child threads.</p>
<p>Phil</p>
]]></content:encoded>
			<wfw:commentRss>http://philsversion.com/2010/06/18/dealing-with-infinite-recursion-redux/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

