<?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>Coding out of procrastination</title>
	<atom:link href="http://www.mattfreeman.co.uk/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.mattfreeman.co.uk</link>
	<description>A developer&#039;s rants and light bulb moments!</description>
	<lastBuildDate>Wed, 25 Aug 2010 06:35:59 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Exporting a RavenDB Index to CSV using Powershell</title>
		<link>http://www.mattfreeman.co.uk/2010/08/exporting-a-ravendb-index-to-csv-using-powershell/</link>
		<comments>http://www.mattfreeman.co.uk/2010/08/exporting-a-ravendb-index-to-csv-using-powershell/#comments</comments>
		<pubDate>Wed, 25 Aug 2010 06:35:59 +0000</pubDate>
		<dc:creator>matt-csharp</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.mattfreeman.co.uk/2010/08/exporting-a-ravendb-index-to-csv-using-powershell/</guid>
		<description><![CDATA[Part of the system I maintain needed to have a CSV (for viewing in Excel) generated daily of line items and their prices, since the information was already transformed and ready to be consumed from a RavenDB Index I used a little Powershell scripting to dump it to a CSV.&#160; Easy, practical and can be [...]]]></description>
			<content:encoded><![CDATA[<p>Part of the system I maintain needed to have a CSV (for viewing in Excel) generated daily of line items and their prices, since the information was already transformed and ready to be consumed from a RavenDB Index I used a little Powershell scripting to dump it to a CSV.&#160; Easy, practical and can be wired up to Task Scheduler in a few minutes. </p>
<p>Since CSVs are generally flat we are explicitly in what we fetch (see $fields variable) this causes Raven to pull only from Lucene index (a thus a lot faster) rather than using the index as doc id lookup. To get full compatibility with Excel you have to be a little careful with encoding, otherwise you have to fallback to the import wizard, with ascii it is double click open, fortunately in this instance we live within the ascii charset.&#160; </p>
<p>At GistHub: <a title="http://gist.github.com/548970" href="http://gist.github.com/548970" target="_blank">http://gist.github.com/548970</a>    </p>
<div class="csharpcode">
<pre class="alt">$baseUrl = <span class="str">&quot;http://localhost:8080&quot;</span></pre>
<pre>$outputFile = <span class="str">&quot;salesexport.csv&quot;</span></pre>
<pre class="alt">$fields = <span class="str">&quot;Manufacturer,ProductName,RetailPrice,ProductCode&quot;</span></pre>
<pre>$fieldsArray = $fields.Split(<span class="str">','</span>)</pre>
<pre class="alt">$startAt = 0;</pre>
<pre>$pagingSize = 100</pre>
<pre class="alt"># Build your Index <span class="kwrd">in</span> RavenDB - best to <span class="kwrd">do</span> your hard work there.</pre>
<pre>&#160;</pre>
<pre class="alt"># script  supports flat indexes so we use fields <span class="kwrd">in</span> query to ensure it pulls</pre>
<pre># from Lucene rather than a Lucene to DocID lookup - and again much faster</pre>
<pre class="alt">&#160;</pre>
<pre>[System.Reflection.Assembly]::Load(<span class="str">&quot;System.Web.Extensions, Version=3.5.0.0,&quot;</span> `</pre>
<pre class="alt">+ <span class="str">&quot;Culture=neutral, PublicKeyToken=31bf3856ad364e35&quot;</span>)</pre>
<pre>$serializer = New-Object System.Web.Script.Serialization.JavaScriptSerializer</pre>
<pre class="alt">$serializer.MaxJsonLength = [System.Int32]::MaxValue # probably too laxed</pre>
<pre>$webClient = New-Object System.Net.WebClient</pre>
<pre class="alt">&#160;</pre>
<pre>#clear the file and write the columns</pre>
<pre class="alt">#<span class="kwrd">using</span> ascii since Excel presumes CSV and has problem open .csv directly when BOM </pre>
<pre>#present. <span class="kwrd">if</span> you need unicode use utf8, save file <span class="kwrd">as</span> .txt and use wizard</pre>
<pre class="alt">[String]::Join(<span class="str">&quot;,&quot;</span>,($fieldsArray | %{ (<span class="str">'&quot;'</span> + $_ + <span class="str">'&quot;'</span>)})) | Out-File -Encoding ascii $outputFile</pre>
<pre>&#160;</pre>
<pre class="alt"><span class="kwrd">do</span> {</pre>
<pre>&#160;</pre>
<pre class="alt">$indexUrl = <span class="str">&quot;$baseUrl/indexes/Shop/Brochure?start=$startAt&amp;pageSize=$pagingSize&amp;&quot;</span> `</pre>
<pre>    + [<span class="kwrd">string</span>]::Join(<span class="str">&quot;&amp;&quot;</span>,($fieldsArray | % { <span class="str">&quot;fetch=$_&quot;</span> } ))</pre>
<pre class="alt">&#160;</pre>
<pre>$response = $webClient.DownloadString($indexUrl)</pre>
<pre class="alt">$jsonDic = $serializer.DeserializeObject($response)</pre>
<pre>&#160;</pre>
<pre class="alt">$results = $jsonDic[<span class="str">&quot;Results&quot;</span>]</pre>
<pre>$script:totalResults =$results.Length</pre>
<pre class="alt">&#160;</pre>
<pre><span class="kwrd">foreach</span>($result <span class="kwrd">in</span> $results)</pre>
<pre class="alt">{</pre>
<pre>&#160;</pre>
<pre class="alt"># ravendb includes the __document_id <span class="kwrd">in</span> the ouput <span class="kwrd">as</span> the last key so </pre>
<pre># we select only fields we specify by <span class="kwrd">using</span> a select -first</pre>
<pre class="alt">[<span class="kwrd">string</span>]::Join(<span class="str">&quot;,&quot;</span>, (% { $result.Keys } | select -first $fieldsArray.Length |`</pre>
<pre>% { (<span class="str">'&quot;'</span> + $result[$_].Replace(<span class="str">&quot;,&quot;</span>,<span class="str">&quot;\,&quot;</span>) + <span class="str">'&quot;'</span>) } )) `</pre>
<pre class="alt">| Out-File -Encoding ascii $outputFile -Append</pre>
<pre>&#160;</pre>
<pre class="alt"># <span class="kwrd">if</span> you want custom mapping just use $result[column-name] to build your own</pre>
<pre>&#160;</pre>
<pre class="alt">}</pre>
<pre>&#160;</pre>
<pre class="alt">$startAt = $startAt + $pagingSize</pre>
<pre>} <span class="kwrd">while</span> ( $script:totalResults -ne 0 )</pre>
</div>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>Again we use the .Net serializer rather than Newtonsoft.Json due to strange errors that I dont have time to troubleshoot, this exports more than 20,000 records in less than a minute (on a modest desktop). Enjoy</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.mattfreeman.co.uk%2F2010%2F08%2Fexporting-a-ravendb-index-to-csv-using-powershell%2F&amp;linkname=Exporting%20a%20RavenDB%20Index%20to%20CSV%20using%20Powershell"><img src="http://www.mattfreeman.co.uk/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://www.mattfreeman.co.uk/2010/08/exporting-a-ravendb-index-to-csv-using-powershell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Moving data from SQL Server to RavenDB using Powershell</title>
		<link>http://www.mattfreeman.co.uk/2010/08/moving-data-from-sql-server-to-ravendb-using-powershell/</link>
		<comments>http://www.mattfreeman.co.uk/2010/08/moving-data-from-sql-server-to-ravendb-using-powershell/#comments</comments>
		<pubDate>Sun, 22 Aug 2010 08:39:11 +0000</pubDate>
		<dc:creator>matt-csharp</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.mattfreeman.co.uk/2010/08/moving-data-from-sql-server-to-ravendb-using-powershell/</guid>
		<description><![CDATA[We have a legacy-style product information database in SQL Server that is updated every few days by the vendor (when I say updated I mean delete tables and recreated – yuck) – we have no control over this database design apart from adding our views (which thankfully they don’t delete) and our front end display [...]]]></description>
			<content:encoded><![CDATA[<p>We have a legacy-style product information database in SQL Server that is updated every few days by the vendor (when I say updated I mean delete tables and recreated – yuck) – we have no control over this database design apart from adding our views (which thankfully they don’t delete) and our front end display database is in RavenDb (document database with restful HTTP interface), one of my goals this weekend was to figure out a simple way to bulk move data periodically from the product database to the document database.&#160; </p>
<p><img src="http://www.mattfreeman.co.uk/images/padiagram.png" alt="dev diagram" /> </p>
<p align="center">
<font size="1">&#160; <br />(simple google docs drawing)</font></p>
<p>Initially I played with Rhino ETL but even that was overkill (and a little slow – but a beautiful framework) so inspired from recently looking at psake I decided to see how far I could get with Powershell sanely. The great thing about using a admin-friendly scripting language like powershell if that is easy to modify if your schema changes and it’s extremely easy to deploy, although it might not be the best code. Due to Powershell’s full .Net support and RavenDB’s restful interface it was pretty easy to get this up and running – and a good opportunity to further enhance my Powershell skills. </p>
<p>Here’s the result &#8211; a rough and simple ETL powershell script for moving data from a SQL Server table to RavenDB, it tries a PATCH first incase the doc already exists, failing that it will do a PUT, since given other properties are set from different sources an overwrite of the document is not going to work for us. </p>
<div class="csharpcode">
<pre class="alt"># requires curl on PATH - <span class="kwrd">if</span> you installed mysysgit with it added to all PATHS then</pre>
<pre># you should be okay, otherwise download from http:<span class="rem">//curl.haxx.se </span></pre>
<pre class="alt">&#160;</pre>
<pre># presume integrated security edit connection otherwise</pre>
<pre class="alt">$sqlserver = <span class="str">&quot;.\SQLEXPRESS&quot;</span> </pre>
<pre>$db = <span class="str">&quot;DATAVENDOR_CAR&quot;</span></pre>
<pre class="alt">$baseUrl = <span class="str">&quot;http://localhost:8080&quot;</span></pre>
<pre># first <span class="kwrd">value</span> selected must be the doc id - ideally create dedicated view instead</pre>
<pre class="alt">$sqlQuery =  <span class="str">&quot;SELECT CarId, Manufacturer, Model,&quot;</span> `</pre>
<pre>  + <span class="str">&quot;Title, BodyStyle, Doors, CO2, Trim, DriveTrain, Transmission,&quot;</span> `</pre>
<pre class="alt">  + <span class="str">&quot;FuelType, EngineSize, ManufacturerRetailPrice, SourceUpdated FROM CarView&quot;</span></pre>
<pre>    </pre>
<pre class="alt">    </pre>
<pre>$connection_string = (<span class="str">&quot;Data Source=$sqlserver; Initial Catalog=$db;Integrated Security=SSPI&quot;</span>)</pre>
<pre class="alt">$conn = New-Object System.Data.SqlClient.SqlConnection($connection_string)</pre>
<pre>&#160;</pre>
<pre class="alt"># newtonsoft.json created weird errors </pre>
<pre>[System.Reflection.Assembly]::Load(<span class="str">&quot;System.Web.Extensions, Version=3.5.0.0, Culture=neutral,</span></pre>
<pre><span class="str"> PublicKeyToken=31bf3856ad364e35&quot;</span>)</pre>
<pre class="alt">$serializer = New-Object System.Web.Script.Serialization.JavaScriptSerializer</pre>
<pre>&#160;</pre>
<pre class="alt">$conn.Open()</pre>
<pre>$cmd = $conn.CreateCommand()</pre>
<pre class="alt">$cmd.CommandText = $sqlQuery</pre>
<pre>$reader = $cmd.ExecuteReader()</pre>
<pre class="alt">&#160;</pre>
<pre>$derivativeIds = New-Object <span class="str">'System.Collections.Generic.List[string]'</span></pre>
<pre class="alt">&#160;</pre>
<pre><span class="kwrd">while</span> ($reader.Read()) {</pre>
<pre class="alt">&#160;</pre>
<pre>    $docid = $reader.GetValue(0)</pre>
<pre class="alt">    $url = ([System.Uri](<span class="str">&quot;$baseUrl/docs/&quot;</span> + $docid)).AbsoluteUri.ToString();</pre>
<pre>&#160;</pre>
<pre class="alt">    # build a list of SET operations - either update or create property</pre>
<pre>    # only affects properties existly set <span class="kwrd">in</span> the operations, does not overwrite </pre>
<pre class="alt">    # whole document. </pre>
<pre>    $listOfSetOperations = New-Object <span class="str">'System.Collections.Generic.List</span></pre>
<pre><span class="str">[System.Collections.Generic.Dictionary[string,object]]'</span></pre>
<pre class="alt">&#160;</pre>
<pre>    <span class="kwrd">for</span> ($i = 1; $i -lt $reader.FieldCount; $i = $i +1)    { </pre>
<pre class="alt">        $dic = New-Object <span class="str">'System.Collections.Generic.Dictionary[string,object]'</span></pre>
<pre>        $dic.Add(<span class="str">&quot;Type&quot;</span>,<span class="str">&quot;set&quot;</span>)</pre>
<pre class="alt">        $dic.Add(<span class="str">&quot;Name&quot;</span>,$reader.GetName($i))</pre>
<pre>        $dic.Add(<span class="str">&quot;Value&quot;</span>,$reader.GetValue($i))</pre>
<pre class="alt">        $listOfSetOperations.Add($dic)</pre>
<pre>     }</pre>
<pre class="alt">    </pre>
<pre>    $jsonPayLoad = $serializer.Serialize($listOfSetOperations).Replace(<span class="str">&quot;`&quot;</span><span class="str">&quot;,&quot;</span><span class="str">'&quot;)</pre>
<pre class="alt">    $response = curl -w '</span>%{HTTP_CODE}<span class="str">' -X PATCH $url &quot;-d $jsonPayLoad&quot;</pre>
<pre>    </pre>
<pre class="alt">    # doc does not exist so lets insert it. I go this route rather than a single update-or-insert PUT </pre>
<pre>    # because if the doc already exists on the ravendb it will have additional properties associated with</pre>
<pre class="alt">    # that have been added/modified since (i.e. new properties dont exist in this sql source db)</pre>
<pre>    </pre>
<pre class="alt">    if($response -eq '</span>404<span class="str">')  {</pre>
<pre>        </pre>
<pre class="alt">        $dictionary = New-Object '</span>System.Collections.Generic.Dictionary[<span class="kwrd">string</span>,<span class="kwrd">object</span>]<span class="str">'</pre>
<pre>        </pre>
<pre class="alt">        for ($i = 0; $i -lt $reader.FieldCount; $i = $i +1)    {</pre>
<pre>            $dictionary.Add($reader.GetName($i),$reader.GetValue($i))</pre>
<pre class="alt">         }</pre>
<pre>        </pre>
<pre class="alt">        $dictionarySerialized = $serializer.Serialize($dictionary).Replace(&quot;`&quot;&quot;,&quot;'</span><span class="str">&quot;) </pre>
<pre>        </pre>
<pre class="alt">        curl -X PUT $url &quot;</span>-d $dictionarySerialized&quot;</pre>
<pre>    }</pre>
<pre class="alt">    </pre>
<pre>}</pre>
</div>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>&#160;</p>
<p>Example also available on gisthub here, adapt it per your needs, <a title="Source on gisthub" href="http://gist.github.com/543499" target="_blank">http://gist.github.com/543499</a>.</p>
<p>I had strange errors relating to Value property with Newtonsoft.Json, so I fell back to .Net Javascript serializer. We could additionally clean this up by using WebClient instead of relying on curl. And of course this is void of any real error handling or performance analytics and as junior to Powershell any best-practices, feel free to extend it, adapt it, it isn’t meant to be beautiful code so don’t punish me too hard. </p>
<p>Later in the week I plan to batch the requests into groups of 50 (or a configurable amount), per the documentation at <a title="http://ravendb.net/documentation/docs-http-batching-2" href="http://ravendb.net/documentation/docs-http-batching-2">http://ravendb.net/documentation/docs-http-batching-2</a> this should significantly improve throughput, I’ll update the script on gisthub.</p>
<p>I used PowerGUI script editor as the main IDE (although it does crash a lot – have process explorer / task manager handy), but for a free tool it’s a good start. For debugging Raven communication add –v parameter to the curl command, or use Fiddler, or plugin WebClient with some verbosity. Also note, by default RavenDb requires authentication for anything other than GET requests so you’ll need to either change the behaviour via the config file or ensure your http requests are authenticated.&#160; </p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.mattfreeman.co.uk%2F2010%2F08%2Fmoving-data-from-sql-server-to-ravendb-using-powershell%2F&amp;linkname=Moving%20data%20from%20SQL%20Server%20to%20RavenDB%20using%20Powershell"><img src="http://www.mattfreeman.co.uk/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://www.mattfreeman.co.uk/2010/08/moving-data-from-sql-server-to-ravendb-using-powershell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CQRS with Async Controllers in ASP.NET MVC 2 and NServiceBus Messaging over MSMQ (that&#8217;s a mouthful)</title>
		<link>http://www.mattfreeman.co.uk/2010/05/cqrs-with-async-controllers-in-asp-net-mvc-2-and-nservicebus-messaging-over-msmq-thats-a-mouthful/</link>
		<comments>http://www.mattfreeman.co.uk/2010/05/cqrs-with-async-controllers-in-asp-net-mvc-2-and-nservicebus-messaging-over-msmq-thats-a-mouthful/#comments</comments>
		<pubDate>Wed, 12 May 2010 17:19:02 +0000</pubDate>
		<dc:creator>matt-csharp</dc:creator>
				<category><![CDATA[async]]></category>
		<category><![CDATA[cqrs]]></category>
		<category><![CDATA[nservicebus]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[mvc]]></category>

		<guid isPermaLink="false">http://www.mattfreeman.co.uk/2010/05/cqrs-with-async-controllers-in-asp-net-mvc-2-and-nservicebus-messaging-over-msmq-thats-a-mouthful/</guid>
		<description><![CDATA[&#160;
My spiking experience this afternoon.
When doing CQRS with a message bus behind the controller, you’ll be tempted to think the only solution is do fire and forget-for-now (remaining completely pure), but often the command system will be processing commands in a fraction of a second, if you hang about a few hundred milliseconds you will [...]]]></description>
			<content:encoded><![CDATA[<p>&#160;</p>
<p><em>My spiking experience this afternoon.</em></p>
<p align="justify">When doing CQRS with a message bus behind the controller, you’ll be tempted to think the only solution is do fire and forget-for-now (remaining completely pure), but often the command system will be processing commands in a fraction of a second, if you hang about a few hundred milliseconds you will probably be able to know if the command succeed or fails, without this you either assume success (fake the result based on the command) or can at the best presume in progress (eg. Amazon – Processing your order – We will email soon).</p>
<p align="justify">Traditionally if you are waiting for an expensive&#160; operation in the web layer could be dangerous, you could easily exhaust the thread pool if the operation is long running (even a few hundred milliseconds could be exhausted with a few hundred or so concurrent connections).</p>
<p align="justify">However with a true asynchronous programming model you need not keep the thread when the operation is not CPU bound.&#160; In the case of file IO and socket IO, the responsibility is moved to the device drivers (a operating system I/O completion port), when the operation is completed, an event loop will reawaken a thread to continue processing.</p>
<p align="justify">In a nutshell if your ASP.Net request is waiting half a second for a response from the command layer it need not be taking up a thread (presuming the right APM practices are followed), when the non CPU bound operations completes an internal event loop will grab a thread (which may or may not be the same that setup the request) and continue processing. This is very similar to asynchronous programming model that has made NodeJS and Twisted on Ruby popular in recent months but the same technology has existed in .Net since 2.0 and some parts since 1.1 (albeit not cleanly in the web layer).</p>
<p align="justify">In NServiceBus the event loop is the NServiceBus worker threads that are created when the bus is started, when a reply arrives on the bus that correlates with message sent it will execute the callback provided (if one exists), in our case this signals to AsyncManager to grab a thread, restore the context (request etc..) and continue processing – calling the XYZCompleted event (with the args the callbacks gives to the AsyncManager).</p>
<p align="justify">My example is using the Async controller functionality in ASP.Net MVC 2.0.&#160; I am using NServiceBus to Send* a message to a specific endpoint and wait for the reply.&#160; Without Async controller functionality we would have to rely on a more inefficient methods such ManualResetEvent which will keep one of your precious ASP.Net web-worker threads tied to the one request, even if you push it back to a ThreadPool it is still taking a thread until you embrace a true APM (asynchronous programming model). </p>
<p align="justify">* (note: we dont do pub/sub from the web layer, we push the command in to the system where, when processed, may or may not generate a serious of events that then can be subsequently publish to interested subscribers)</p>
<div class="csharpcode">&#160;</div>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">using</span> System;</pre>
<pre><span class="kwrd">using</span> System.Linq;</pre>
<pre class="alt"><span class="kwrd">using</span> System.Web.Mvc;</pre>
<pre><span class="kwrd">using</span> NBusEcoClient.Messages;</pre>
<pre class="alt"><span class="kwrd">using</span> NBusEcoClient.Web.Filters;</pre>
<pre><span class="kwrd">using</span> NServiceBus;</pre>
<pre class="alt">&#160;</pre>
<pre><span class="kwrd">namespace</span> NBusEcoClient.Web.Controllers</pre>
<pre class="alt">{</pre>
<pre>    <span class="kwrd">public</span> <span class="kwrd">class</span> BookPurchaseController : AsyncController</pre>
<pre class="alt">    {</pre>
<pre>        <span class="kwrd">private</span> <span class="kwrd">readonly</span> IBus bus;</pre>
<pre class="alt">&#160;</pre>
<pre>        <span class="kwrd">public</span> BookPurchaseController(IBus bus)</pre>
<pre class="alt">        {</pre>
<pre>            <span class="kwrd">this</span>.bus = bus;</pre>
<pre class="alt">        }</pre>
<pre>&#160;</pre>
<pre class="alt">        [AsyncTimeout(250)]</pre>
<pre>        [SwallowNsbTimeoutAsCompletionResult]</pre>
<pre class="alt">        <span class="kwrd">public</span> <span class="kwrd">void</span> OrderAsync(OrderCommand orderCommand)</pre>
<pre>        {</pre>
<pre class="alt">            AsyncManager.OutstandingOperations.Increment();</pre>
<pre>&#160;</pre>
<pre class="alt">            <span class="kwrd">if</span> (orderCommand.IsValid())</pre>
<pre>            {</pre>
<pre class="alt">                bus.Send(orderCommand).Register(ar =&gt;</pre>
<pre>                                        {</pre>
<pre class="alt">                                            AsyncManager.Parameters[<span class="str">&quot;completionResult&quot;</span>] =</pre>
<pre>                                                ar.AsyncState <span class="kwrd">as</span> CompletionResult;</pre>
<pre class="alt">                                            AsyncManager.OutstandingOperations.Decrement();</pre>
<pre>                                        }, orderCommand);</pre>
<pre class="alt">&#160;</pre>
<pre>                <span class="kwrd">return</span>;</pre>
<pre class="alt">            }</pre>
<pre>&#160;</pre>
<pre class="alt">            AsyncManager.Parameters[<span class="str">&quot;completionResult&quot;</span>] = </pre>
<pre>                <span class="kwrd">new</span> CompletionResult {ErrorCode = (<span class="kwrd">int</span>) CommandResult.Failure};</pre>
<pre class="alt">            AsyncManager.OutstandingOperations.Decrement();</pre>
<pre>        }</pre>
<pre class="alt">&#160;</pre>
<pre>        <span class="kwrd">public</span> ActionResult OrderCompleted(CompletionResult completionResult)</pre>
<pre class="alt">        {</pre>
<pre>            <span class="kwrd">if</span> (completionResult.ErrorCode == (<span class="kwrd">int</span>) (CommandResult.NoError))</pre>
<pre class="alt">            {</pre>
<pre>                <span class="kwrd">return</span> OrderSuccessful();</pre>
<pre class="alt">            }</pre>
<pre>&#160;</pre>
<pre class="alt">            <span class="kwrd">if</span> (completionResult.ErrorCode == (<span class="kwrd">int</span>) (CommandResult.StillProcessing))</pre>
<pre>            {</pre>
<pre class="alt">                <span class="rem">// Not received a reply for &gt; 250ms, perhaps cmd servers are  busy.</span></pre>
<pre>                <span class="rem">// We'll return in progress - command received and valid</span></pre>
<pre class="alt">                <span class="kwrd">return</span> OrderInProgress();</pre>
<pre>            }</pre>
<pre class="alt">&#160;</pre>
<pre>            <span class="kwrd">if</span> (completionResult.ErrorCode == (<span class="kwrd">int</span>) (CommandResult.Failure))</pre>
<pre class="alt">            {</pre>
<pre>                <span class="rem">// Command has failed – is it a domain failure or not. // missing: affect on tranx?</span></pre>
<pre class="alt">&#160;</pre>
<pre>                OrderNotAcceptedMessage domainError = completionResult.Messages</pre>
<pre class="alt">                    .Where(m =&gt; m.GetType().Equals(<span class="kwrd">typeof</span> (OrderNotAcceptedMessage)))</pre>
<pre>                    .Cast&lt;OrderNotAcceptedMessage&gt;().FirstOrDefault();</pre>
<pre class="alt">&#160;</pre>
<pre>                <span class="kwrd">return</span> OrderFailure(domainError != <span class="kwrd">null</span> ? </pre>
<pre class="alt">                    domainError.ErrorMessage : <span class="str">&quot;Generic error&quot;</span>);</pre>
<pre>            }</pre>
<pre class="alt">            <span class="kwrd">throw</span> <span class="kwrd">new</span> ArgumentException(<span class="str">&quot;Unexpected completion result: &quot;</span> + </pre>
<pre>                completionResult.ErrorCode);</pre>
<pre class="alt">        }</pre>
<pre>&#160;</pre>
<pre class="alt">        <span class="kwrd">protected</span> ActionResult OrderFailure(<span class="kwrd">string</span> message)</pre>
<pre>        {</pre>
<pre class="alt">            ViewData[<span class="str">&quot;Error&quot;</span>] = message;</pre>
<pre>            <span class="kwrd">return</span> View(<span class="str">&quot;OrderFailure&quot;</span>);</pre>
<pre class="alt">        }</pre>
<pre>&#160;</pre>
<pre class="alt">        <span class="kwrd">protected</span> ActionResult OrderSuccessful()</pre>
<pre>        {</pre>
<pre class="alt">            <span class="kwrd">return</span> View(<span class="str">&quot;OrderProcessed&quot;</span>);</pre>
<pre>        }</pre>
<pre class="alt">&#160;</pre>
<pre>        <span class="kwrd">protected</span> ActionResult OrderInProgress()</pre>
<pre class="alt">        {</pre>
<pre>            <span class="kwrd">return</span> View(<span class="str">&quot;OrderInProgress&quot;</span>);</pre>
<pre class="alt">        }</pre>
<pre>    }</pre>
<pre class="alt">}</pre>
</div>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>&#160;</p>
</p>
<p align="justify">Because our controller inherits from AsyncController rather than Controller we split our action over the non CPU bound operation (i.e. waiting for a correlated reply) , in this case Order is called just like a synchronized action, the AsyncController takes care of choosing the proper method dispatcher based on XAsync&#160; and XCompleted where X is the action&#160; name.</p>
<p align="justify">Because we actually expect the timeout to be non-fatal occurrence (infact it will probably be regular) we need to coerce the TimeoutException and handle it as a non-exception. One could use an ActionFilter like this to do this:</p>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<div class="csharpcode">
<pre class="alt"> <span class="kwrd">public</span> <span class="kwrd">class</span> SwallowNsbTimeoutAsCompletionResult : ActionFilterAttribute</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">void</span> OnActionExecuted(ActionExecutedContext filterContext)</pre>
<pre>        {</pre>
<pre class="alt">            <span class="kwrd">bool</span> hasTimeoutException = (filterContext.Exception <span class="kwrd">as</span> TimeoutException) != <span class="kwrd">null</span>;</pre>
<pre>&#160;</pre>
<pre class="alt">            <span class="kwrd">if</span>( hasTimeoutException)</pre>
<pre>            {</pre>
<pre class="alt">                var actionDescriptor =</pre>
<pre>                    filterContext.ActionDescriptor <span class="kwrd">as</span> ReflectedAsyncActionDescriptor;</pre>
<pre class="alt">&#160;</pre>
<pre>                filterContext.ExceptionHandled = <span class="kwrd">true</span>;</pre>
<pre class="alt">&#160;</pre>
<pre>                filterContext.Result = actionDescriptor.CompletedMethodInfo</pre>
<pre class="alt">                            .Invoke(filterContext.Controller</pre>
<pre>                                    , <span class="kwrd">new</span> <span class="kwrd">object</span>[]</pre>
<pre class="alt">                                            {</pre>
<pre>                                    <span class="kwrd">new</span> CompletionResult</pre>
<pre class="alt">                                        {</pre>
<pre>                                            ErrorCode = (<span class="kwrd">int</span>) (CommandResult.StillProcessing)</pre>
<pre class="alt">                                        }</pre>
<pre>                                }) <span class="kwrd">as</span> ActionResult;</pre>
<pre class="alt">            }</pre>
<pre>        }</pre>
<pre class="alt">    }</pre>
</div>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>
  <br />If you dont extend further then in simple examples you can simplify and use this instead:</p>
<div class="csharpcode">
<pre class="alt">[HandleError(ExceptionType = <span class="kwrd">typeof</span>(TimeoutException), View = <span class="str">&quot;InProgress&quot;</span>)]</pre>
</div>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>&#160;</p>
<p>A more tricky step that remains is to clear out the correlated map on the IBus, this will leak and we are no longer interested in correlating the response to the callback* after the timeout as a view would have been returned to the client and connection lost,&#160; (ajax scenarios may differ will polling (and more so with websockets).</p>
<p>* note: you may still be interested in the response but just not the callback handling it</p>
<p>I haven’t got a great way to do this yet since the field is private but here’s a snippet to get you going (maybe schedule a cleanup every minute). If only NServiceBus was on GitHub, I’ve uninstalled SVN now <img src='http://www.mattfreeman.co.uk/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> </p>
<div class="csharpcode">
<pre class="alt"> var messageIdToAsyncHandlerPrivateProperty = bus.GetType()</pre>
<pre>                            .GetField(<span class="str">&quot;messageIdToAsyncResultLookup&quot;</span>, BindingFlags.Instance | BindingFlags.NonPublic);</pre>
<pre class="alt">&#160;</pre>
<pre>                    var mappingDictionary = messageIdToAsyncHandlerPrivateProperty.GetValue(bus)</pre>
<pre class="alt">                        <span class="kwrd">as</span> IDictionary&lt;<span class="kwrd">string</span>,NServiceBus.Unicast.BusAsyncResult&gt;;</pre>
<pre>&#160;</pre>
<pre class="alt">                    <span class="kwrd">lock</span>(mappingDictionary) {</pre>
<pre>&#160;</pre>
<pre class="alt">                        var toRemove = mappingDictionary.Where(busResult =&gt; <span class="kwrd">true</span>);  </pre>
<pre>                        <span class="rem">// change predicate to something like to determine non interested one</span></pre>
<pre class="alt">                        <span class="rem">// busResult =&gt; ((IMessageWithExpiringCallBackInterest)(busResult.State)).Sent &gt; 1sec</span></pre>
<pre>                        <span class="kwrd">foreach</span>(var removeSubject from toRemove)</pre>
<pre class="alt">                            mappingDictionary.Remove(removeSubject);</pre>
<pre>                    }</pre>
</div>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>I have asked UdiDahan about making this protected so we can extend UnicastBus to handle such scenarios. </p>
<p>If you are interested in the reply after the response has gone then add a normal Handler and make sure the message handler is associated when the bus is created, both the callback and handler will fire (the callback first if exists), you may need to set a flag (isHandled) in the header of current message context if both are going to do similar behaviours. However don&#8217;t use a handler on the web layer to for example send “order failed” email, this should be published from the domain layer and something subscribes to it and publishes, maybe in same process or maybe different process/node communicated pub/sub with NServiceBus.</p>
<p>On service side you return a result and optionally a message, NServiceBus sends these as one CompletionResult (or at least aggregates them into one). For example:</p>
<div class="csharpcode">
<pre class="alt"><span class="rem">// success</span></pre>
<pre>            bus.Return((<span class="kwrd">int</span>)CommandResult.NoError);</pre>
<pre class="alt">&#160;</pre>
<pre>            <span class="rem">// command failure</span></pre>
<pre class="alt">            bus.Reply(<span class="kwrd">new</span> OrderNotAcceptedMessage() { ErrorMessage = <span class="str">&quot;Credit not available&quot;</span> } );</pre>
<pre>            bus.Return((<span class="kwrd">int</span>)CommandResult.Failure);</pre>
</div>
<p>&#160;</p>
<p>Disclaimers:</p>
<ul>
<li>This is not production code, it was just a dirty spike, Im not an expert, I may be wrong, I wouldnt use this code in production! </li>
<li>MVC: You obviously don’t do string magic like that, you should probably embrace Thunderdome principle and you could probably move a lot of NSB/Async logic to something like MyOpinionatedAsyncController. </li>
<li>Commands. No distinguish between domain error and failures, infact the wording is probably wrong here, and I need to investigate further about scenarios where transaction is rollbacked.</li>
<li>This is just an eye opener to some techniques, I hope you learnt something</li>
</ul>
<p>References:</p>
<ul>
<li><a href="http://www.microsoft.com/learning/en/us/book.aspx?ID=6522&amp;locale=en-us" target="_blank">Asynchronous programming chapter in C# via CLR 2nd edition</a></li>
<li><a href="http://tech.groups.yahoo.com/group/nservicebus/message/5322?threaded=1&amp;var=1&amp;p=1" target="_blank">Memory leak for uncalled callbacks</a> in NSB</li>
<li><a href="http://nservicebus.com/Documentation.aspx" target="_blank">NServiceBus documentation</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ee728598(v=VS.100).aspx" target="_blank">Using an Asynchronous Controller in ASP.NET MVC</a></li>
<li><a href="http://code.msdn.microsoft.com/aspnetmvcsamples/Release/ProjectReleases.aspx?ReleaseId=3547" target="_blank">Async source sample from MSDN</a></li>
<p><a></a></p>
</ul>
<p>Twitter folks that discuss CQRS, NserviceBus, regularly etc.. <a href="http://www.twitter.com/mattcodes" target="_blank">mattcodes</a> (me), <a href="http://www.twitter.com/udidahan" target="_blank">UdiDahan</a> (author of NSB), @<a href="http://www.twitter.com/andreasohlund" target="_blank">andreasohlund</a>, @<a href="http://www.twitter.com/Daneel3001" target="_blank">Daneel3001</a>, @<a href="http://www.twitter.com/neilrobbins" target="_blank">neilrobbins</a>, @<a href="http://www.twitter.com/pvjds" target="_blank">pvjds</a></p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.mattfreeman.co.uk%2F2010%2F05%2Fcqrs-with-async-controllers-in-asp-net-mvc-2-and-nservicebus-messaging-over-msmq-thats-a-mouthful%2F&amp;linkname=CQRS%20with%20Async%20Controllers%20in%20ASP.NET%20MVC%202%20and%20NServiceBus%20Messaging%20over%20MSMQ%20%28that%26rsquo%3Bs%20a%20mouthful%29"><img src="http://www.mattfreeman.co.uk/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://www.mattfreeman.co.uk/2010/05/cqrs-with-async-controllers-in-asp-net-mvc-2-and-nservicebus-messaging-over-msmq-thats-a-mouthful/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Closures &amp; Scope in JavaScript vs C#</title>
		<link>http://www.mattfreeman.co.uk/2010/03/closures-scope-in-javascript-vs-c/</link>
		<comments>http://www.mattfreeman.co.uk/2010/03/closures-scope-in-javascript-vs-c/#comments</comments>
		<pubDate>Wed, 31 Mar 2010 04:33:26 +0000</pubDate>
		<dc:creator>matt-csharp</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[closures]]></category>
		<category><![CDATA[scope]]></category>

		<guid isPermaLink="false">http://www.mattfreeman.co.uk/2010/03/closures-scope-in-javascript-vs-c/</guid>
		<description><![CDATA[I’ve thought for a while that closures in JavaScript are handled almost the same as in C# 3, ignore underlying mechanics, however watching Robert Nyman talk at ØreDev thrown a spanner in my understanding.&#160; He asserted the opposite of what I was lead to believe (coming from a C# background) without associating it with an [...]]]></description>
			<content:encoded><![CDATA[<p>I’ve thought for a while that closures in JavaScript are handled almost the same as in C# 3, ignore underlying mechanics, however watching Robert Nyman talk at <a href="http://vimeo.com/channels/oredev" target="_blank">ØreDev</a> thrown a spanner in my understanding.&#160; He asserted the opposite of what I was lead to believe (coming from a C# background) without associating it with an earlier revelation he made about the language (which I hope this post clarifies).</p>
<p>Take the following C&#8217;# snippet I’ve cooked up: (1)</p>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">using</span> System;</pre>
<pre><span class="kwrd">using</span> System.Collections.Generic;</pre>
<pre class="alt">&#160;</pre>
<pre><span class="kwrd">namespace</span> ConsoleApplication1</pre>
<pre class="alt">{</pre>
<pre>    <span class="kwrd">internal</span> <span class="kwrd">class</span> Program</pre>
<pre class="alt">    {</pre>
<pre>        <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Main(<span class="kwrd">string</span>[] args)</pre>
<pre class="alt">        {</pre>
<pre>            var myIntegerPrinters = <span class="kwrd">new</span> List&lt;Action&gt;();</pre>
<pre class="alt">&#160;</pre>
<pre>            <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i &lt; 5; i++)</pre>
<pre class="alt">            {</pre>
<pre>                <span class="kwrd">int</span> currentIndex = i;</pre>
<pre class="alt">                myIntegerPrinters.Add(() =&gt; Console.WriteLine(currentIndex));</pre>
<pre>            }</pre>
<pre class="alt">&#160;</pre>
<pre>            <span class="kwrd">foreach</span> (Action intPrinter <span class="kwrd">in</span> myIntegerPrinters)</pre>
<pre class="alt">            {</pre>
<pre>                intPrinter.Invoke();</pre>
<pre class="alt">            }</pre>
<pre>&#160;</pre>
<pre class="alt">            Console.Read();</pre>
<pre>        }</pre>
<pre class="alt">    }</pre>
<pre>}</pre>
</div>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
</p>
<p>This code (1) prints out 0, 1, 2, 3, 4 as expected, since we create a closure around currentIndex which is set on each iteration of the loop to the current value of i (copied by value).&#160; </p>
<p>Now try this in JavaScript (Firebug console window will suffice): (2)</p>
<div class="csharpcode">
<pre class="alt">            var myIntegerPrinters = [];</pre>
<pre>&#160;</pre>
<pre class="alt">            <span class="kwrd">for</span> (var i = 0; i &lt; 5; i++)</pre>
<pre>            {</pre>
<pre class="alt">                var currentIndex = i;</pre>
<pre>                myIntegerPrinters.push(function () { console.log(currentIndex); } );</pre>
<pre class="alt">            }</pre>
<pre>&#160;</pre>
<pre class="alt">            <span class="kwrd">for</span> each (var intPrinter <span class="kwrd">in</span> myIntegerPrinters)</pre>
<pre>            {</pre>
<pre class="alt">                intPrinter();</pre>
<pre>            }</pre>
<pre class="alt">&#160;</pre>
</div>
<div class="csharpcode">&#160;</div>
<div class="csharpcode">&#160;</div>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>You might expect this to produce the same result as the C# code as we too create a closure around currentIndex, however this snippet prints out 4,4,4,4,4. Yikes. </p>
<p>This had me puzzled for a minute or two and then it dinged.</p>
<p>JavaScript <strong>does not have block scope</strong>, only function scope, and this is critical to remember not just for where you define your variables but also in the case of closures considerations. </p>
<p>The code below (3) is by meaning the same as (2), for illustration we move the currentIndex out of the for loop block, essentially due to absence of block scope this how JavaScript interprets the code from (2), as you can see each closure will reference the same currentIndex as the others, which is incremented up until 4.</p>
<div class="csharpcode">
<pre class="alt">            var currentIndex = 0;</pre>
<pre>            var myIntegerPrinters = [];</pre>
<pre class="alt">&#160;</pre>
<pre>            <span class="kwrd">for</span> (var i = 0; i &lt; 5; i++)</pre>
<pre class="alt">            {</pre>
<pre>                currentIndex++;</pre>
<pre class="alt">                myIntegerPrinters.push(function () { console.log(currentIndex); } );</pre>
<pre>            }</pre>
<pre class="alt">&#160;</pre>
<pre>            <span class="kwrd">for</span> each (var intPrinter <span class="kwrd">in</span> myIntegerPrinters)</pre>
<pre class="alt">            {</pre>
<pre>                intPrinter();</pre>
<pre class="alt">            }</pre>
</div>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>&#160;</p>
<p>Of course, this prints out 4,4,4,4,4. In listing (2) despite it appearing as new declaration, JavaScript just silently ignores the repeated var and refers to the current currentIndex in the scope (the function scope). C#, the strict language that it is, due to its block scope, would produce an error that it cannot be declared due to different meaning in the scope etc.. so you have a safeguard from the compiler there which JavaScript does not have.</p>
<p>Inner function scope to the rescue, as Robert Nyman illustrates (in between all the crazy celebrity lust – what is all that about?), you can overcome this like this:</p>
<div class="csharpcode">
<pre class="alt">var myIntegerPrinters = [];</pre>
<pre>&#160;</pre>
<pre class="alt">    <span class="kwrd">for</span> (var i = 0; i &lt; 5; i++)</pre>
<pre>    {</pre>
<pre class="alt">       myIntegerPrinters.push((function (currentIndex) { </pre>
<pre>            <span class="kwrd">return</span> <span class="kwrd">new</span> function() { console.log(currentIndex); };</pre>
<pre class="alt">         }(i)));</pre>
<pre>    }</pre>
<pre class="alt">&#160;</pre>
<pre>    <span class="kwrd">for</span> each (intPrinter <span class="kwrd">in</span> myIntegerPrinters)</pre>
<pre class="alt">    {</pre>
<pre>        intPrinter();</pre>
<pre class="alt">    }</pre>
<pre>&#160;</pre>
</div>
<p>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>This of course, due to function scope, prints out 0,1,2,3,4. And voila we have achieve the same as the C# code in listing (1) albeit with a little more work.&#160; </p>
<p>Just a heads up for C# devs embracing JavaScript and its coolness, be careful of the absence of block scope, JavaScript won’t tell you or warn you and it could be that bug that you spend half a day on <img src='http://www.mattfreeman.co.uk/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  See <a href="http://vimeo.com/channels/oredev" target="_blank">ØreDev</a> and Robert Nyman talk for more JavaScript goodness.</p>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.mattfreeman.co.uk%2F2010%2F03%2Fclosures-scope-in-javascript-vs-c%2F&amp;linkname=Closures%20%26amp%3B%20Scope%20in%20JavaScript%20vs%20C%23"><img src="http://www.mattfreeman.co.uk/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://www.mattfreeman.co.uk/2010/03/closures-scope-in-javascript-vs-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NodeJS JSON Data Services &amp; JavaScript web scraping fu</title>
		<link>http://www.mattfreeman.co.uk/2010/03/nodejs-json-data-services-javascript-web-scraping-fu/</link>
		<comments>http://www.mattfreeman.co.uk/2010/03/nodejs-json-data-services-javascript-web-scraping-fu/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 01:13:03 +0000</pubDate>
		<dc:creator>matt-csharp</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[async]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[nodejs]]></category>
		<category><![CDATA[scraping]]></category>

		<guid isPermaLink="false">http://www.mattfreeman.co.uk/2010/03/nodejs-json-data-services-javascript-web-scraping-fu/</guid>
		<description><![CDATA[Minor update:&#160; tidy code (19/03/2010)
NodeJS (http://www.nodejs.org) is an event driven non-blocking (all operations are non-blocking) JavaScript hosting engine, very lightweight and very fast – due to its reliance on the performant Google V8 engine, it’s also very easy using NodeJS to expose JSON data services in just a dozen lines of code.&#160; The non-blocking architecture [...]]]></description>
			<content:encoded><![CDATA[<p><em>Minor update:&#160; <a href="http://fixee.org/paste/88y4i22/" target="_blank">tidy code</a> (19/03/2010)</em></p>
<p><strong>NodeJS</strong> (<a href="http://www.nodejs.org">http://www.nodejs.org</a>) is an event driven non-blocking (all operations are non-blocking) JavaScript hosting engine, very lightweight and very fast – due to its reliance on the performant Google V8 engine, it’s also very easy using NodeJS to expose JSON data services in just a dozen lines of code.&#160; The non-blocking architecture of NodeJS might seem unconventional at first compared to C#/Java, especially the heavy use of callbacks everywhere, but essentially it means that you no longer have threads waiting for IO completion operations (this handed off the OS and underlying interrupts). NodeJS is single threaded – but when the thread is running it is entirely non-blocking thus will complete as fast as your processor can handle, this single threading nature doesn&#8217;t limit capacity but the exact opposite, thread context switching is expensive.</p>
<p>In my example, I collect the arrival details of airplanes destined for the beautiful Koh Samui every five minutes and place them into a global cache, the request logic then just reads the cache and spits out a JSON representation, from the perspective of the client the operation is as fast as one can achieve.</p>
<p>Given the time I spent in the early days of my career writing scrapping software (in C#) for a popular money comparison site, I thought it would be nice to revisit the area in a more dynamic event fashion, thus the collection operation in my case is web scraping, but this could easily be any other procedure such as database* or file reads, again asynchronous in nature out the box. <em>*support varies – PostgreSQL seems to be the choice at the moemnt.</em></p>
<p>If you’re familiar with JavaScript in the browser then the remainder of code should be identical to what you’d use elsewhere, i.e.&#160; basic language constructs, regular expressions, nature of callbacks and closures etc..</p>
<p>For the page retrieval logic, due to the way flightstats.co.uk splits the data by 3hr period on their site, we have to fire off eight page requests to get an overview of the full 24hrs, this is all done asynchronously and afforded by the event driven nature of NodeJS, no need to explicitly setup worker threads or a thread pool, just pure simplisticity.</p>
<p>Creating a server endpoint to publish the data takes just 5 lines. A JSON stingify utility is already included with NodeJS as an added treat (very useful for debugging too – output the whole object).</p>
<p><em>Note: </em>To build NodeJS you’ll need to download the latest package from <a href="http://nodejs.org/">http://nodejs.org/</a> and follow the installation instructions. On Ubuntu Linux you’ll also need to install cmake and buildessentials from apt-get before you install NodeJS so that you have the cxx compiler.</p>
<p><em>Note: This code is exampleware to demonstrate the power of NodeJS, there is no error handling, the regular expressions are fragile, and flightstats.co.uk already expose developer friendly API via web services that should be used instead of regular expression. </em></p>
<div style="overflow: hidden" class="csharpcode">
<pre class="alt"><span class="kwrd">var</span> sys = require(<span class="str">'sys'</span>)</pre>
<pre><span class="kwrd">var</span> http = require(<span class="str">'http'</span>);</pre>
<pre class="alt">&#160;</pre>
<pre>&#160;</pre>
<pre class="alt">(<span class="kwrd">function</span>(options) {</pre>
<pre>  </pre>
<pre class="alt">  <span class="kwrd">var</span> arrivingFlights = <span class="kwrd">new</span> Array();</pre>
<pre>  </pre>
<pre class="alt">  <span class="kwrd">var</span> util = { trim: <span class="kwrd">function</span>( text ) {</pre>
<pre>        <span class="kwrd">return</span> (text || <span class="str">&quot;&quot;</span>).replace( rtrim, <span class="str">&quot;&quot;</span> );</pre>
<pre class="alt">    }};</pre>
<pre>  </pre>
<pre class="alt">  <span class="kwrd">var</span> rtrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g</pre>
<pre>  <span class="kwrd">var</span> baseUrl = <span class="str">&quot;/go/weblet?guid=c228b59beca1b817:44617f82:117d601a4c6:221f&amp;weblet=status&amp;action=AirportFlightStatus&amp;airportCode=USM&amp;airportQueryType=1&quot;</span>;</pre>
<pre class="alt">  <span class="kwrd">var</span> host = <span class="str">&quot;www.flightstats.com&quot;</span>;</pre>
<pre>  <span class="kwrd">var</span> refer = <span class="str">&quot;http://www.samuiairportonline.com/flight-status&quot;</span>;</pre>
<pre class="alt">  <span class="kwrd">var</span> userAgent = <span class="str">&quot;Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6&quot;</span>;</pre>
<pre>    </pre>
<pre class="alt">  <span class="kwrd">var</span> retrieve = <span class="kwrd">function</span>(url,complete) </pre>
<pre>  {</pre>
<pre class="alt">      <span class="kwrd">var</span> flightStat = http.createClient(80, host);</pre>
<pre>      <span class="kwrd">var</span> request = flightStat.request(<span class="str">&quot;GET&quot;</span>, url,</pre>
<pre class="alt">                      {<span class="str">&quot;Host&quot;</span>: host</pre>
<pre>                    , <span class="str">&quot;Referer&quot;</span>: refer</pre>
<pre class="alt">                    , <span class="str">&quot;User-Agent&quot;</span>: userAgent });</pre>
<pre>      request.addListener(<span class="str">'response'</span>, <span class="kwrd">function</span>(response)</pre>
<pre class="alt">      {      </pre>
<pre>      response.setBodyEncoding(<span class="str">&quot;utf8&quot;</span>); </pre>
<pre class="alt">      <span class="kwrd">var</span> body = <span class="str">&quot;&quot;</span>;</pre>
<pre>      response.addListener(<span class="str">'data'</span>, <span class="kwrd">function</span>(chunk)  {   body += chunk;  });</pre>
<pre class="alt">      response.addListener(<span class="str">'end'</span>, <span class="kwrd">function</span>()  {   complete(body);  });</pre>
<pre>      });</pre>
<pre class="alt">      request.close();</pre>
<pre>  }</pre>
<pre class="alt">  </pre>
<pre>  <span class="kwrd">var</span> updateFlightTimes = <span class="kwrd">function</span>() </pre>
<pre class="alt">  {</pre>
<pre>    <span class="kwrd">var</span> completedCounter = 0; <span class="rem">// reset </span></pre>
<pre class="alt">    <span class="kwrd">var</span> lastArrivingFlights = <span class="kwrd">new</span> Array();</pre>
<pre>    </pre>
<pre class="alt">    <span class="rem">// copy over the global collection only after all 8 result sets have returned</span></pre>
<pre>    <span class="kwrd">var</span> completed = <span class="kwrd">function</span>() {   <span class="kwrd">if</span>(completedCounter++ &amp;&amp; completedCounter == 8 )    arrivingFlights = lastArrivingFlights;      };</pre>
<pre class="alt">    </pre>
<pre>    <span class="kwrd">var</span> processTable = <span class="kwrd">function</span>(page)</pre>
<pre class="alt">    {</pre>
<pre>      <span class="kwrd">var</span> tableContent = page.match(/<span class="kwrd">class</span>=<span class="str">&quot;tableListingTable&quot;</span>[^&gt;]+&gt;([^]*)&lt;\/table&gt;/gmi)[0];</pre>
<pre class="alt">      <span class="kwrd">var</span> rowRegExp =  /&lt;tr&gt;\s*?&lt;td[^&gt;]*?&gt;\s*?&lt;a[^&gt;]*?&gt;([^&lt;]*?)&lt;\/a&gt;\s*?(?:&lt;span[^&gt;]*&gt;.*?&lt;\/span&gt;)?\s*?&lt;\/td&gt;\s*?&lt;td[^&gt;]*?&gt;([^&lt;]*?)&lt;\/td&gt;\s*?&lt;td[^&gt;]*?&gt;\s*?\(\s*?&lt;a[^&gt;]*&gt;.*?&lt;\/a&gt;\s*?\)([^&lt;]*?)&lt;\/td&gt;\s*?&lt;td[^&gt;]*?&gt;([^&lt;]*?)&lt;/mgi;</pre>
<pre>      <span class="kwrd">while</span>(rowMatch = rowRegExp.exec(tableContent)) </pre>
<pre class="alt">      {</pre>
<pre>    lastArrivingFlights.push({ code: util.trim(rowMatch[1]), </pre>
<pre class="alt">                  carrier: util.trim(rowMatch[2]), </pre>
<pre>                  origin: util.trim(rowMatch[3]),     </pre>
<pre class="alt">                    arriveTime: util.trim(rowMatch[4]) });    </pre>
<pre>      }</pre>
<pre class="alt">      completed();     </pre>
<pre>    };</pre>
<pre class="alt">    </pre>
<pre>    <span class="rem">// full 24hr period - have to pull 8 pages back</span></pre>
<pre class="alt">    <span class="kwrd">for</span>(<span class="kwrd">var</span> i = 1; i &lt;= 8; i++)</pre>
<pre>    {</pre>
<pre class="alt">      retrieve(baseUrl + <span class="str">&quot;&amp;airportQueryTimePeriod=&quot;</span> + i,processTable);</pre>
<pre>    }</pre>
<pre class="alt">  }</pre>
<pre>  </pre>
<pre class="alt">  updateFlightTimes();</pre>
<pre>  setInterval(updateFlightTimes,options.updateInterval); </pre>
<pre class="alt">&#160;</pre>
<pre>  http.createServer(<span class="kwrd">function</span> (req, res) {</pre>
<pre class="alt">      res.writeHead(200, {<span class="str">'Content-Type'</span>: <span class="str">'application/json'</span>});</pre>
<pre>      res.write(JSON.stringify(arrivingFlights));</pre>
<pre class="alt">      res.close();</pre>
<pre>  }).listen(8000);</pre>
<pre class="alt">&#160;</pre>
<pre>})({ updateInterval: 300000 });</pre>
<pre class="alt">&#160;</pre>
</div>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>
  <br /><em>Code is also on fixee.org at </em><a href="http://fixee.org/paste/88y4i22/">http://fixee.org/paste/88y4i22/</a><font color="#0066cc"></font></p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.mattfreeman.co.uk%2F2010%2F03%2Fnodejs-json-data-services-javascript-web-scraping-fu%2F&amp;linkname=NodeJS%20JSON%20Data%20Services%20%26amp%3B%20JavaScript%20web%20scraping%20fu"><img src="http://www.mattfreeman.co.uk/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://www.mattfreeman.co.uk/2010/03/nodejs-json-data-services-javascript-web-scraping-fu/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Debugging JavaScript Closures &#8211; Browser Optimizations we don&#8217;t want (yet)</title>
		<link>http://www.mattfreeman.co.uk/2010/03/debugging-javascript-closures-browser-optimizations-we-dont-want-yet/</link>
		<comments>http://www.mattfreeman.co.uk/2010/03/debugging-javascript-closures-browser-optimizations-we-dont-want-yet/#comments</comments>
		<pubDate>Tue, 16 Mar 2010 12:25:28 +0000</pubDate>
		<dc:creator>matt-csharp</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[chrome]]></category>
		<category><![CDATA[closures]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[dragonfly]]></category>
		<category><![CDATA[firebug]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://www.mattfreeman.co.uk/2010/03/debugging-javascript-closures-browser-optimizations-we-dont-want-yet/</guid>
		<description><![CDATA[Closures (a function instance coupled with local variables from its environment that are necessary for its execution – B. Katz) are an intrinsic part of the JavaScript language and if you have done more than a few lines of simple JavaScript you have used them whether consciously or not, especially if working with the jQuery [...]]]></description>
			<content:encoded><![CDATA[<p>Closures (<em>a function instance coupled with local variables from its environment that are necessary for its execution – B. Katz</em>) are an intrinsic part of the JavaScript language and if you have done more than a few lines of simple JavaScript you have used them whether consciously or not, especially if working with the jQuery library and/or Ajax callbacks.&#160; </p>
<p>I really like Closures, however I hate debugging when it involves closures, for the simple fact that my favourite JavaScript tool Firebug with Firefox has severe problems evaluating (during a break) on variables that form part of the closure.&#160; An unhelpful “Reference Error: x is not defined” is all we get, where x is the variable name.&#160; Hovering over the variable or using the command window does not work either.    </p>
<p>An experiment on previous versions of FF/FB and in Ubuntu linux was even more disappointing with “break on all errors” not working correctly either, so from what I understand this is a non-platform specific issue (please correct me otherwise).</p>
<p>I use this simple code to illustrate (jQuery dependency) the issue with debugging closures:</p>
<p>&#160;</p>
<div class="csharpcode">
<pre class="alt">$(<span class="kwrd">function</span>()</pre>
<pre>  {</pre>
<pre class="alt">     <span class="kwrd">var</span> myName = <span class="str">&quot;matt&quot;</span>;</pre>
<pre>      <span class="kwrd">var</span> otherNames = [<span class="str">&quot;ted&quot;</span>,<span class="str">&quot;john&quot;</span>,<span class="str">&quot;matt&quot;</span>,<span class="str">&quot;fred&quot;</span>];</pre>
<pre class="alt">    </pre>
<pre>     $.each(otherNames, <span class="kwrd">function</span>()</pre>
<pre class="alt">           {</pre>
<pre>                   <span class="kwrd">var</span> result;</pre>
<pre class="alt">                 </pre>
<pre>                   <span class="kwrd">if</span>(<span class="kwrd">this</span> == myName)</pre>
<pre class="alt">                   {</pre>
<pre>                      result = <span class="kwrd">this</span> + <span class="str">&quot; is SAME as &quot;</span>  + myName;</pre>
<pre class="alt">                   } <span class="kwrd">else</span> {</pre>
<pre>                       result = <span class="kwrd">this</span> + <span class="str">&quot; is not same as &quot;</span> +  myName;</pre>
<pre class="alt">                   }</pre>
<pre>              </pre>
<pre class="alt">                    $(<span class="str">'&lt;p&gt;'</span> + result + <span class="str">'&lt;/p&gt;'</span>).appendTo(<span class="str">'#matchResults'</span>);</pre>
<pre>                       </pre>
<pre class="alt">           });</pre>
<pre>  });</pre>
<pre class="alt">​</pre>
</div>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>&#160;</p>
<p><strong>Note:</strong> For the jQuery savy amongst us I concede that this is overly verbose.</p>
<p>For the paste bin complete with fancy HTML <a href="http://jsbin.com/iduka/2/edit">click here</a>. </p>
<p>Here’s the result in <strong>Firefox 3.6:</strong></p>
<p><a href="http://www.mattfreeman.co.uk/wp-content/uploads/2010/03/closures1.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="closures1" border="0" alt="closures1" src="http://www.mattfreeman.co.uk/wp-content/uploads/2010/03/closures1-thumb.png" width="684" height="469" /></a> </p>
<p>As you can see the runtime (Firefox JavaScript engine &#8211; TraceMonkey) can correctly evaluate myName (otherwise we’d never branch into the <strong><em>if</em></strong>&#160; block) but unfortunately either due to a Firebug bug or the optimization that the TraceMonkey engine makes we can not see the value in the Watch window. Some have suggested that due to optimizations there is not enough profile data to determine myName from the debugging environment. </p>
<p><strong>Google Chrome </strong>and its V8 engine does much better in this respect, not only can it evaluate myName, but it also gives me a breakdown of what variables are local and which are part of the closure. Sweet. Unfortunately in this instance, it wouldn&#8217;t break on the breakpoint I set, but at least it stopped on the next available point (outside the if/else block), presumably this is because Chrome’s V8 engine was able to optimize the branch (maybe due to the data being available at load time). Chrome also does syntax highlighting on JavaScript &#8211; just not on inline scripts. </p>
<p><a href="http://www.mattfreeman.co.uk/wp-content/uploads/2010/03/closures2.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="closures2" border="0" alt="closures2" src="http://www.mattfreeman.co.uk/wp-content/uploads/2010/03/closures2-thumb.png" width="692" height="478" /></a> </p>
</p>
<p>Next up,<strong> Internet Explorer 8</strong>, I didn’t expect much from the IE team (after a let down with IE6 and IE7), but their new Developer Tools proved me wrong, loaded very fast, evaluated myName correctly and even nice color syntax highlighting, you can tell they have been influenced by Firebug design but why not? It works very nice.</p>
<p><a href="http://www.mattfreeman.co.uk/wp-content/uploads/2010/03/closures3.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="closures3" border="0" alt="closures3" src="http://www.mattfreeman.co.uk/wp-content/uploads/2010/03/closures3-thumb.png" width="697" height="326" /></a></p>
<p>I include <strong>Opera 10.5</strong> for good measure however despite their trumpeting about DragonFly I found it very poor like a pre v1 beta of Firebug. One can not add anything to the watch window, can not hover on source code to expose values, I even had to switch to the command window to evaluate myName (at least it did better than Firebug in this case though).</p>
<p><a href="http://www.mattfreeman.co.uk/wp-content/uploads/2010/03/closures4.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="closures4" border="0" alt="closures4" src="http://www.mattfreeman.co.uk/wp-content/uploads/2010/03/closures4-thumb.png" width="705" height="428" /></a></p>
<p>I know the Apple fanboys would hit me with their new iPads if I didn’t include <strong>Safari 4</strong>, I wish I had suitable VM to download this bloat to (30.2mb just for a browser), the scarifies I make in the name of blogging.&#160; But hold up, this looks familiar, the same Web Inspector as Chrome – I always thought WebKit was just the renderer. But something interesting has happened unlike Chrome, this breaks in the correct place, and reveals the closure variable, this is exactly what I wanted. This may be a postitive side-effect that Safari&#8217;s JavaScript engine is less optimizing than Chrome&#8217;s V8 but for debugging I can spare a few extra nanoseconds. I eat my words, Safari for JavaScript debugging is pretty good. Like Chrome, Safari also does syntax highlighting on JavaScript &#8211; just not on inline scripts.</p>
<p><a href="http://www.mattfreeman.co.uk/wp-content/uploads/2010/03/closures5.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="closures5" border="0" alt="closures5" src="http://www.mattfreeman.co.uk/wp-content/uploads/2010/03/closures5-thumb.png" width="723" height="499" /></a> </p>
<p>In conclusion, there are more tools for debugging JavaScript against the DOM than just Firebug, whilst Firebug is still my favourite at least I’ve discovered some alternatives for when Firebug just can’t deliver. Surprisingly <strong>Safari is now my first backup choice</strong>.</p>
<p> I’d be interested in hearing workarounds (other than promoting the variable to global) and possible configuration options to disable JavaScript optimizations when debugging – please leave in the comments. </p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.mattfreeman.co.uk%2F2010%2F03%2Fdebugging-javascript-closures-browser-optimizations-we-dont-want-yet%2F&amp;linkname=Debugging%20JavaScript%20Closures%20%26ndash%3B%20Browser%20Optimizations%20we%20don%26rsquo%3Bt%20want%20%28yet%29"><img src="http://www.mattfreeman.co.uk/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://www.mattfreeman.co.uk/2010/03/debugging-javascript-closures-browser-optimizations-we-dont-want-yet/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Saved by a yield &#8211; Bulking NHibernate Read-only Data</title>
		<link>http://www.mattfreeman.co.uk/2009/08/save-by-a-yield-bulking-nhibernate-read-only-data/</link>
		<comments>http://www.mattfreeman.co.uk/2009/08/save-by-a-yield-bulking-nhibernate-read-only-data/#comments</comments>
		<pubDate>Thu, 06 Aug 2009 08:15:52 +0000</pubDate>
		<dc:creator>matt-csharp</dc:creator>
				<category><![CDATA[nhibernate]]></category>
		<category><![CDATA[iterator]]></category>
		<category><![CDATA[yield]]></category>

		<guid isPermaLink="false">http://www.mattfreeman.co.uk/2009/08/save-by-a-yield-bulking-nhibernate-read-only-data/</guid>
		<description><![CDATA[&#160;
I&#8217;ve just finished working on a service which exports information from a legacy database once per day, in a nutshell retrieve, map, publish. 
In a four-step process it works as follow:

Query the data layer for records modified after last run date (~24hrs) 
Load the records into a domain model (responsibility of NHibernate) 
 Convert the [...]]]></description>
			<content:encoded><![CDATA[<p>&#160;</p>
<p>I&#8217;ve just finished working on a service which exports information from a legacy database once per day, in a nutshell retrieve, map, publish. </p>
<p>In a four-step process it works as follow:</p>
<ul>
<li>Query the data layer for records modified after last run date (~24hrs) </li>
<li>Load the records into a domain model (responsibility of NHibernate) </li>
<li> Convert the collection to our flat shared schema DTOs (AutoMapper)</li>
<li>Publish the messages to the bus (NServiceBus / MSMQ)</li>
</ul>
<p>Whilst performance wasn&#8217;t a noted priority it still had to complete the daily job within a few hours and with the resources a basic server afforded. In the initial stages of implementation, I had my integration tests running against a SQLite database and performance wise everything was progressing smoothly. However when we pointed it against a production database (SQL Server) with a six figure number of aggregate instead of less than 100 for test data we soon hit problems, dreaded out of memory exceptions.&#160; </p>
<p>It didn&#8217;t take long to pinpoint the issue was related the data access strategy, bringing all the entities out of the database at once made the Session balloon at shocking rate, in a hindsight a bad approach to begin with. This was a showstopper, and with it approaching 5pm, and happy hour on the beach finishing at 7pm, I could already see this turning out to be disappointing.</p>
<p>I contemplated a few ideas, changing some settings with regards to mutability (we are doing read-only), switching to an IStatelessSession, and even polluting the consumer to use some paging mechanism&#8230;. I played around for while and then I thought about a yield inside the service layer, essentially implementing my own iterator to keep the unit of work small and thus underlying NHibernate session minimal. </p>
<p>In my service layer and wherever possible I favour IEnumerable over IList, for the definition I had: </p>
<p>IEnumerable&lt;Derivative&gt; GetDerivativesWithPriceChanges(DateTime laterThan)</p>
<p>And for the code (<em>refactor due</em>):</p>
<pre class="csharpcode">  <span class="kwrd">public</span> IEnumerable&lt;Derivative&gt; GetDerivativesWithPriceChanges(DateTime laterThan)
        {
            Expression&lt;Func&lt;Derivative, <span class="kwrd">bool</span>&gt;&gt; predicate = d =&gt; d.PricingUpdated &gt; laterThan;

            <span class="kwrd">int</span> bufferSize = 10; <span class="rem">// make configurable, inject</span>
            <span class="kwrd">int</span> marker = 0;
            <span class="kwrd">int</span> lastAmountRetrieved = 0;

            <span class="kwrd">do</span>
            {

                <span class="kwrd">using</span> (UOW.Start())
                {
                    var selection
                        = <span class="kwrd">new</span> Func&lt;IQueryable&lt;Derivative&gt;, IQueryable&lt;Derivative&gt;&gt;
                            (d =&gt; d.Skip(marker).Take(bufferSize));

                    var derivatives = derivativeRepository.GetByQuery(predicate, selection).ToList();

                    lastAmountRetrieved = derivatives.Count;

                    <span class="kwrd">foreach</span> (var derivative <span class="kwrd">in</span> derivatives)
                    {
                        <span class="kwrd">yield</span> <span class="kwrd">return</span> derivative;
                    }
                }

                marker = marker + bufferSize;

            } <span class="kwrd">while</span> (lastAmountRetrieved == bufferSize);

            <span class="kwrd">yield</span> <span class="kwrd">break</span>;

        }</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>)</p>
<p>Inside GetDerivativesWithPriceChanges, I&#8217;m paging through the database opening and closing the Unit of work after a specified number of entities are returned. <strong>Note: </strong>UOW system provides the underlying ISession to the repositories, although my UOW differs slights I recommend analysing Ayende’s Rhino Commons for a good example. </p>
<p>Best of all the consumer of the service is none the wiser, the code for paging was already on the base repository (as simple as Skip(x).Take(y) with NHibernate.Linq), and as an added benefit we have quicker feedback to our logging system and on our integration tests.&#160; It&#8217;s certainly not the purist implementation, but since I was working with read-only data it turned out perfect for this scenario and I was enjoying a Heineken by the beach by 6.30pm. I imagine I will eventually refactor the some of the logic for readonly paging/uow streaming to its own class, but for today, check-in, and close solution. <img src='http://www.mattfreeman.co.uk/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>A few lessons learnt:</p>
<ol>
<li>Memory is <strike>not</strike> never infinite. </li>
<li>Long running operations are bad for integration tests, these tests are often already a magnitude slower than unit tests so keep them trim. </li>
<li>Always consider the data and quantity of which you&#8217;ll be working with in production. If unsure, ask. </li>
<li>The problem is rarely solely NHibernate but usually the high-level approach taken to tackle the problem, don&#8217;t damn the NHibernate Session. </li>
</ol>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.mattfreeman.co.uk%2F2009%2F08%2Fsave-by-a-yield-bulking-nhibernate-read-only-data%2F&amp;linkname=Saved%20by%20a%20yield%20%26ndash%3B%20Bulking%20NHibernate%20Read-only%20Data"><img src="http://www.mattfreeman.co.uk/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://www.mattfreeman.co.uk/2009/08/save-by-a-yield-bulking-nhibernate-read-only-data/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NHibernate &amp; Linq &#8211; Free yourself from NHibernate</title>
		<link>http://www.mattfreeman.co.uk/2009/05/nhibernate-linq-free-yourself-from-nhibernate/</link>
		<comments>http://www.mattfreeman.co.uk/2009/05/nhibernate-linq-free-yourself-from-nhibernate/#comments</comments>
		<pubDate>Sun, 24 May 2009 07:24:23 +0000</pubDate>
		<dc:creator>matt-csharp</dc:creator>
				<category><![CDATA[nhibernate]]></category>
		<category><![CDATA[linq]]></category>
		<category><![CDATA[nhlinq]]></category>

		<guid isPermaLink="false">http://www.mattfreeman.co.uk/2009/04/nhibernate-linq-free-yourself-from-nhibernate/</guid>
		<description><![CDATA[Note: This is tested against 2.0 not the 2.1 Beta. Today I’ve been experimenting with NHibernate.Linq against the GA release, there are apparently a few issues and a new version under development which takes a different approach rather than parsing to the criteria API, but hopefully the public API should be the similar whatever version [...]]]></description>
			<content:encoded><![CDATA[<p><b>Note: This is tested against 2.0 not the 2.1 Beta.</b> Today I’ve been experimenting with NHibernate.Linq against the GA release, there are apparently a few issues and a new version under development which takes a different approach rather than parsing to the criteria API, but hopefully the public API should be the similar whatever version gets released. </p>
<p>In the past I’ve hated leaking ICriteria/DetachedCriteria out of the repository, in addition with a lot of the business logic being pushed down into infrastructure code it always felt a little dirty.&nbsp; Whatever approach I’ve taken there has always been some aspect that didn’t feel right, I’ve always been concerned that I’ve have NH—&gt;DB rather than it just being an implementation of the infrastructure that’s wired in at the end, thankfully with NHibernate and Linq there is some light at the end of the tunnel. I’ve haven’t finalised my approach yet, I’ve still got some internal debating to do about location of the query and services and possibly the integrating the specification pattern (now it’s easy to consume), but I think I’m going to take a slight reversal on my previous post.</p>
<p>This is what I’m liking. </p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">virtual</span> IEnumerable&lt;T&gt; GetByQuery
            (Expression&lt;Func&lt;T, <span class="kwrd">bool</span>&gt;&gt; predicate,
             Func&lt;IQueryable&lt;T&gt;, IQueryable&lt;T&gt;&gt; selectionPredicate)
        {
            <span class="kwrd">using</span> (ITransaction tx = Session.BeginTransaction())
            {
                <span class="kwrd">try</span>
                {
                    IQueryable&lt;T&gt; query = Session.Linq&lt;T&gt;().Where(predicate);
                   <span class="kwrd">return</span> selectionPredicate(query);
                }
                <span class="kwrd">catch</span> (HibernateException hibernateException)
                {
                    tx.Rollback();
                    <span class="kwrd">throw</span> <span class="kwrd">new</span> RepositoryException(hibernateException);
                }
            }
        }
</pre>
<pre class="csharpcode">&nbsp;</pre>
<p>In my service layer or outer repository etc..:</p>
<pre class="csharpcode">&nbsp;</pre>
<pre class="csharpcode">
            Expression&lt;Func&lt;Hotel, <span class="kwrd">bool</span>&gt;&gt; predicate = hotel=&gt;
                  hotel.Stars &gt; 3 &amp;&amp; hotel.Country == Country.UK

           Func&lt;IEnumerable&lt;Hotel&gt;,IEnumerable&lt;Hotel&gt;&gt; selectionPredicate = col =&gt;
                          col.Skip(10).Take(10); <span class="rem">// pagingSetup.GetQueryForPage(requestedPage);</span>

            var hotels = hotelRepository.GetByQuery(predicate, selectionPredicate);
            <span class="kwrd">return</span> hotels;
   </pre>
<p><style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
</p>
<p>I fired up Ayende’s cool NH Profiler and the above does get converted to a single neat parameterized SQL statement with correct selection of the paging. This also significantly aids in testability as injecting a in-memory repository in place of NH into the service layer is now super easy just execute the expressions as is on the collection (I won’t even post the code for that)…&nbsp; In future I might not even be working with NHibernate – so this approach gives me great flexibility with no query logic trapped in HQL or the NH criteria api – who knows – it could be couchdb etc.. <img src='http://www.mattfreeman.co.uk/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.mattfreeman.co.uk%2F2009%2F05%2Fnhibernate-linq-free-yourself-from-nhibernate%2F&amp;linkname=NHibernate%20%26amp%3B%20Linq%20%26ndash%3B%20Free%20yourself%20from%20NHibernate"><img src="http://www.mattfreeman.co.uk/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://www.mattfreeman.co.uk/2009/05/nhibernate-linq-free-yourself-from-nhibernate/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NHibernate &#8211; Opinionated Style</title>
		<link>http://www.mattfreeman.co.uk/2009/01/nhibernate-opinionated-software/</link>
		<comments>http://www.mattfreeman.co.uk/2009/01/nhibernate-opinionated-software/#comments</comments>
		<pubDate>Sat, 31 Jan 2009 15:18:35 +0000</pubDate>
		<dc:creator>matt-csharp</dc:creator>
				<category><![CDATA[nhibernate]]></category>

		<guid isPermaLink="false">http://www.mattfreeman.co.uk/2009/01/nhibernate-opinionated-software/</guid>
		<description><![CDATA[NHibernate supports several programming paradigms that allows you to write what I consider good code, some of the ideas expressed in this post are opinionated and the merit of such should be reviewed against your own coding preferences and applicability to your project.
Creation
NHibernate requires each mapped type to have a parameterless constructor &#8211; However, this [...]]]></description>
			<content:encoded><![CDATA[<p>NHibernate supports several programming paradigms that allows you to write what I consider good code, some of the ideas expressed in this post are opinionated and the merit of such should be reviewed against your own coding preferences and applicability to your project.</p>
<p><strong>Creation</strong></p>
<p>NHibernate requires each mapped type to have a parameterless constructor &#8211; However, this parameterless constructor does not need to pollute your domain model as it can be hidden from external code by marking it with <em>protected</em> or <em>protected internal</em> whilst your parameterized constructors can be <em>public</em> , meaning you can still enforce integrity at the constructor level, thus never allowing for creation of invalid entities. If for some reason you never want to create a Dog without a date of birth you could enforce this whilst still using NHibernate by doing something as simple as this:</p>
<div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &#39;Courier New&#39;, courier, monospace; background-color: #f4f4f4">
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> Dog
{
    <span style="color: #0000ff">protected internal </span> Dog() { }

    <span style="color: #0000ff">public</span> Dog(DateTime dateOfBirth)
    {
        <span style="color: #0000ff">this</span>.dateOfBirth = dateOfBirth;
    }

    <span style="color: #0000ff">private</span> DateTime dateOfBirth;
    <span style="color: #0000ff">public</span> DateTime DateOfBirth
    {
        get
        {
            <span style="color: #0000ff">return</span> dateOfBirth;
        }
        <span style="color: #0000ff">protected</span> set
        {
            dateOfBirth = <span style="color: #0000ff">value</span>;
        }
    }
}</pre>
</div>
<p><em>(You could optionally use an automatic property if using C# 3.0)</em></p>
<p>Where you don&#8217;t require a separate factory I&#8217;ve personally taken to creation static methods to give some more semantic meaning to the creation. Here&#8217;s a trivial example, but this style really comes into its own when you have multiple constructor parameter sets that have the same signature, not only do the static method names gives meaning, but you can&#8217;t vary a constructor unless you vary its parameter set too.</p>
<div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &#39;Courier New&#39;, courier, monospace; background-color: #f4f4f4">
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">        <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> Dog CreateFromEstimatedAge(<span style="color: #0000ff">int</span> estimatedAge)
        {
            var dog = <span style="color: #0000ff">new</span> Dog {isEstimated = <span style="color: #0000ff">false</span>,
                               dateOfBirth = DateTime.Now.AddYears(-estimatedAge)};
            <span style="color: #0000ff">return</span> dog;
        }</pre>
</div>
<p>&#160;</p>
<p>2) <strong>Encapsulation</strong></p>
<p>Classes that contain nothing but public virtual <em>type</em> <em>name</em> { get; set; } are potentially a big code smell.&#160; To preserve encapsulation one needs to carefully consider the visibility of each member and any constraints that should be imposed on the setters.&#160; For example, if you had a database key that was a simple auto-increment identity that required no visibility then you have no good reason to define a public setter for this property. On brownfield projects you should also consider if you need to map everything that&#8217;s in the database, if you&#8217;ve already gone past that point, use either the inbuilt tools or Resharper to find usage of properties (or rather where no usage exists).</p>
<p>2b) <strong>Don&#8217;t expose IList</strong></p>
<p>These are big smells as far as I&#8217;m considered, when you do something like person.Children.Add(new Child(&quot;Fabio&quot;)) you&#8217;re violating the &quot;tell, don&#8217;t ask principle&quot;, you should be delegating the work of adding a child to the person, however subtly in this case you&#8217;re asking for the collection of children and doing the work yourself.&#160; You should expose methods &quot;AddChild()&quot; &#8211; which throws it own meaningful exception when constraints are violated, and return an IEnumerable of Children via the .Children property (getter only). I disagree with throwing a not implemented via your own collection or not supported via a read only list since where a class implements a particular interface it should be substitutable without worry, I shouldn&#8217;t have to know that underneath it is a read only collection or a list stole of its owed behaviour.</p>
<p>Most consumers of an IList I&#8217;ve seen in projects use only the iterator and the Count property &#8211; which is available via Linq extensions method of Count() &#8211; perhaps not as efficient but I&#8217;m willing to make this tiny sacrifice. Linq extensions method also provide numerous other operations over IEnumerables including sorting, selection, projection etc.. Expose the lowest common interface of IEnumerable and you&#8217;ll be able to change the underlying concrete implementation as you please.&#160; Avoid creating your own collection type to handle constraints as this adds extra work and in my experience quite often the constraints that govern the collection are owned and unique to the particular type of parent.</p>
<p>4) <strong>Validation</strong></p>
<p>You should be throwing a suitable exception if immediately possible when a call to a setter is attempting to put the object into an invalid state. So person.Age = -5 should throw ArgumentException. If a string property can not be null or empty, throw an ArgumentNullException when null and an ArgumentException when empty, follow the BCL conventions.&#160; Where more complex validation is carried out and it is the responsibility of the object to perform this validation then move away from properties, where properties run for more than a few lines or make calls to foreign objects (exception of lazy loading) then its time to consider moving them to methods.</p>
<p>I&#8217;ve seen a couple of people object to immediate validation, preferring to allow consumers to push the object into a known invalid state and then call IsValid or Validate or something similar (and even some delegating this to Interceptors etc..), but you can still achieve summary/delayed validation whilst not weakening your domain integrity which I&#8217;ll demonstrate in another blog post in a few days.</p>
<p>5) <strong>Repository</strong></p>
<p>There&#8217;s been a lot of talk on generic repositories recently, I&#8217;m definitely a fan of hiding the generic repository in an inner repository, exposing find all by criteria style methods on the domain repository gives away too much of its own responsibility as well probably leaking some ORM specific dependencies out of your repository (think DetachedCriteria), and even NHibernate.ObjectNotFoundException etc.. This style of repository I think works quite well:</p>
<div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &#39;Courier New&#39;, courier, monospace; background-color: #f4f4f4">
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">using</span> System;

<span style="color: #0000ff">namespace</span> Cruisers.Ecommerce.Domain.Repository
{
  <span style="color: #0000ff">public</span> <span style="color: #0000ff">interface</span> ICruiseRepository
  {
      IEnumerable&lt;ICruise&gt; GetCruisesOnDate(DateTime date);
      IEnumerable&lt;ICruise&gt; GetCruisesThatAreDiscounted();
      ICruise GetCruiseById(<span style="color: #0000ff">int</span> id);
      ICruise GetCruiseByBrokerCodeName(<span style="color: #0000ff">string</span> codeName);
  }
}

<span style="color: #0000ff">namespace</span> Cruises.Ecommerce.DataAccess
{
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> NHCruiseRepository : ICruiseRepository
    {
        <span style="color: #0000ff">private</span> <span style="color: #0000ff">readonly</span> IDaoRepository&lt;Cruise&gt; daoRepository;

        <span style="color: #0000ff">public</span> NHCruiseRepository(IDaoRepository&lt;Cruise&gt; daoRepository)
        {
            <span style="color: #0000ff">this</span>.daoRepository = daoRepository;
        }

        <span style="color: #0000ff">public</span> IEnumerable&lt;ICruise&gt; GetCruisesOnDate(DateTime date)
        {
            <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> System.NotImplementedException();
        }

        <span style="color: #0000ff">public</span> IEnumerable&lt;ICruise&gt; GetCruisesThatAreDiscounted()
        {
            <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> System.NotImplementedException();
        }

        <span style="color: #0000ff">public</span> ICruise GetCruiseById(<span style="color: #0000ff">int</span> id)
        {
            <span style="color: #0000ff">try</span>
            {
               <span style="color: #0000ff">return</span> daoRepository.Get(id);
            } <span style="color: #0000ff">catch</span>(NHibernate.ObjectNotFoundException nhException)
            {
               <span style="color: #008000">// throw new ArgumentOutOfRangeException(&quot;id&quot;,&quot;cruise not found&quot;,nhException);</span>
                <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> CruiseNotFoundException(<span style="color: #006080">&quot;cruise with id &quot;</span> + id + <span style="color: #006080">&quot; not found.&quot;</span>,nhException);
            }
        }

        <span style="color: #0000ff">public</span> ICruise GetCruiseByCodeName(<span style="color: #0000ff">string</span> codeName)
        {
            <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> System.NotImplementedException();
        }
    }

}

<span style="color: #0000ff">namespace</span> Cruisers.Common
{
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">interface</span> IDaoRepository&lt;T, K&gt;
    {
        T Get(K id);
        IList&lt;T&gt; FindAll(DetachedCritiera critiera);
    }
}</pre>
</div>
<p>But eventually you may reach a point when you have to consider sorting, paging, etc.. in these cases one can create a Query object to nicely encapsulate sorting and paging options and provide methods to accept such e.g.</p>
<div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &#39;Courier New&#39;, courier, monospace; background-color: #f4f4f4">
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">IEnumerable&lt;ICruise&gt; GetCruisesOnDate(OnDateQuery onDateQuery)</pre>
</div>
<p>As a further improvement in 2.1 we&#8217;ll be able to elegantly use the specification pattern (you can today but it is some work) and have the NH repository convert the predicates to NH queries, I intend to spike an example from the trunk soon. NH 2.1 will give us the ability to use Linq natively, but I recommend you avoid exposing this as you&#8217;ll have query logic (admittedly NH clean) thrown throughout your application, instead we harness the forthcoming Linq power to use clean specifications instead.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.mattfreeman.co.uk%2F2009%2F01%2Fnhibernate-opinionated-software%2F&amp;linkname=NHibernate%20%26%238211%3B%20Opinionated%20Style"><img src="http://www.mattfreeman.co.uk/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://www.mattfreeman.co.uk/2009/01/nhibernate-opinionated-software/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Powershell Productivity</title>
		<link>http://www.mattfreeman.co.uk/2009/01/powershell-productivity/</link>
		<comments>http://www.mattfreeman.co.uk/2009/01/powershell-productivity/#comments</comments>
		<pubDate>Mon, 19 Jan 2009 20:25:30 +0000</pubDate>
		<dc:creator>matt-csharp</dc:creator>
				<category><![CDATA[powershell]]></category>
		<category><![CDATA[productivity]]></category>
		<category><![CDATA[shell]]></category>

		<guid isPermaLink="false">http://www.mattfreeman.co.uk/2009/01/powershell-productivity/</guid>
		<description><![CDATA[Powershell can be a tricky shell to learn but it&#8217;s worth it, it&#8217;s a great .Net based scripting environment that once familiar you&#8217;ll quite happily alias cmd to it and wish that you had the same intuitive environment on your linux counterparts. Scott Hanselmann was right years ago when evangelising this great product and it [...]]]></description>
			<content:encoded><![CDATA[<p>Powershell can be a tricky shell to learn but it&#8217;s worth it, it&#8217;s a great .Net based scripting environment that once familiar you&#8217;ll quite happily alias cmd to it and wish that you had the same intuitive environment on your linux counterparts. Scott Hanselmann was right years ago when evangelising this great product and it is a shame that I&#8217;m only embracing it now.</p>
<p>Here&#8217;s a few snippets that I&#8217;ve used in the past few days. They are a bit verbose at this stage, but it&#8217;s all part of the learning, hopefully one day I might be answering your Powershell questions over on StackOverflow.com.</p>
<p>1) Run this in a solution directory and it will produce a summary of classes that contain Tests, it will sum the number of tests and group the tests by Directory. Admittedly this took me 15 minutes to write, but probably would take less than a minute if I had to restart</p>
<div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &#39;Courier New&#39;, courier, monospace; background-color: #f4f4f4">
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">PS C:\dev\pxan&gt; gci -rec -include <span style="color: #006080">&quot;*.cs&quot;</span>  | where { ($numberTests = $(gc $_.FullName | where { $_.ToString() -match <span style="color: #006080">&quot;\[Te
st\]&quot;</span> }).Count );($numberTests -gt 0) } | where { $numberTests -gt 0 } | <span style="color: #0000ff">select</span> @{n=<span style="color: #006080">&quot;Name&quot;</span>;e= { $_.Name }}, @{n=<span style="color: #006080">&quot;Directo
ry&quot;</span>; e={$_.Directory }},@{n=<span style="color: #006080">&quot;NumberOfTests&quot;</span>;e={ $numberTests }} | group -<span style="color: #0000ff">property</span> Directory | foreach { Write-Host $_.Na
<span style="color: #0000ff">me</span>; (foreach { $_.Group } | <span style="color: #0000ff">Select</span> Name, NumberOfTests ) }

C:\dev\pxan\Shark.Client\Tests

Name                                                                                                      NumberOfTests
----                                                                                                      -------------
FormBucketTests.cs                                                                                                   14
FormDataExtractorTests.cs                                                                                            17
ProcSessionTests.cs                                                                                                  13</pre>
</div>
<p>2) Show me the top five CPU consuming processes,&#160; hmm.. This Windows Live Mesh consumes a lot more power than FolderShare.</p>
<div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &#39;Courier New&#39;, courier, monospace; background-color: #f4f4f4">
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">PS C:\Documents <span style="color: #0000ff">and</span> Settings\Matt Freeman&gt; gps | sort CPU -desc | <span style="color: #0000ff">select</span> -first 5

<span style="color: #0000ff">Handles</span>  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    695      24    62800      81644   226   206.94    504 Moe
    526      19    51548      38548   346    54.52   2784 WindowsLiveWriter
    459       9     3412       1656    45    26.41    692 lsass
   1116       0        0        240     2     9.52      4 System
    173       6    26436      29200    78     9.44   1864 nod32krn</pre>
</div>
<p>3) Occasionally I find myself needing to search through a directory of files for a particular string in a file (eg. a database credentials in some PHP app etc..). You could substitute the extra $true to filter further down by modified date, or file size, or extension etc..</p>
<div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &#39;Courier New&#39;, courier, monospace; background-color: #f4f4f4">
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">PS C:\dev\phpcms&gt; gci -rec | where { $fileName = $_.Name; $<span style="color: #0000ff">true</span>}  |  gc -ErrorAction SilentlyContinue | where { $_.Contains
(<span style="color: #006080">&quot;password&quot;</span>) }   | foreach { Write-Host $fileName <span style="color: #006080">&quot; ::::: &quot;</span>  $_  }
setup.php  :::::    $password = <span style="color: #006080">&quot;abc&quot;</span>;
adminsetup.php :::::    $password = <span style="color: #006080">&quot;abc&quot;</span>;</pre>
</div>
<p>I&#8217;ve found that the standard powershell application fine for performing most shell tasks although this week I&#8217;m going to wrap some of snippets I used regularly into scripts in which I&#8217;d probably use an IDE like PowerShell Analyzer for such.</p>
<p>What&#8217;s also pretty cool is that one can use powershell from build scripts so I forsee this replacing some of less obviously syntax I&#8217;ve had to use to achieve tasks in MSBuild and NAnt directly.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.mattfreeman.co.uk%2F2009%2F01%2Fpowershell-productivity%2F&amp;linkname=Powershell%20Productivity"><img src="http://www.mattfreeman.co.uk/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://www.mattfreeman.co.uk/2009/01/powershell-productivity/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
