<?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>mookid on code</title>
	<atom:link href="http://mookid.dk/oncode/feed" rel="self" type="application/rss+xml" />
	<link>http://mookid.dk/oncode</link>
	<description>computers are cool</description>
	<lastBuildDate>Sun, 07 Mar 2010 09:00:24 +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>More checking out MongoDB:&#160;Querying</title>
		<link>http://mookid.dk/oncode/archives/1145</link>
		<comments>http://mookid.dk/oncode/archives/1145#comments</comments>
		<pubDate>Sun, 07 Mar 2010 09:00:24 +0000</pubDate>
		<dc:creator>mookid</dc:creator>
				<category><![CDATA[mongodb]]></category>
		<category><![CDATA[nifty]]></category>

		<guid isPermaLink="false">http://mookid.dk/oncode/?p=1145</guid>
		<description><![CDATA[In my first post about MongoDB, I touched querying very lightly. Querying is of course pretty important to most systems, so it&#8217;s fair to dedicate a separate post to the subject.
Querying in MongoDB works by sending a document to the server, e.g. in the following snippet I create a document with a post ID

var somePost [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://mookid.dk/oncode/archives/1057">first post</a> about MongoDB, I touched querying very lightly. Querying is of course pretty important to most systems, so it&#8217;s fair to dedicate a separate post to the subject.</p>
<p>Querying in MongoDB works by sending a document to the server, e.g. in the following snippet I create a document with a post ID</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> somePost <span style="color: #339933;">=</span> db.<span style="color: #660066;">posts</span>.<span style="color: #660066;">findOne</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span><span style="color: #3366CC;">&quot;_id&quot;</span><span style="color: #339933;">:</span> ObjectId<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;00112233445566778899aabb&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span></pre></div></div>

<p>- which can actually be even shorter, as the <code>find</code> and <code>findOne</code> functions accept an <code>ObjectId</code> directly as their argument, like so:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> somePost <span style="color: #339933;">=</span> db.<span style="color: #660066;">posts</span>.<span style="color: #660066;">findOne</span><span style="color: #009900;">&#40;</span>ObjectId<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;00112233445566778899aabb&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span></pre></div></div>

<p>But how can I find a post with a specific slug? Easy, like so:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> somePost <span style="color: #339933;">=</span> db.<span style="color: #660066;">posts</span>.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>slug<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;this-slug-probably-comes-from-a-url&quot;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span></pre></div></div>

<p>But how does this perform? It&#8217;s easy to examine how queries are executed with the <code>explain()</code> function, like so:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&gt;</span> db.<span style="color: #660066;">posts</span>.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>slug<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;this-slug-probably-comes-from-a-url&quot;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">explain</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
        <span style="color: #3366CC;">&quot;cursor&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;BasicCursor&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #3366CC;">&quot;startKey&quot;</span> <span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span>
&nbsp;
        <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
        <span style="color: #3366CC;">&quot;endKey&quot;</span> <span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span>
&nbsp;
        <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
        <span style="color: #3366CC;">&quot;nscanned&quot;</span> <span style="color: #339933;">:</span> <span style="color: #CC0000;">10000</span><span style="color: #339933;">,</span>
        <span style="color: #3366CC;">&quot;n&quot;</span> <span style="color: #339933;">:</span> <span style="color: #CC0000;">1</span><span style="color: #339933;">,</span>
        <span style="color: #3366CC;">&quot;millis&quot;</span> <span style="color: #339933;">:</span> <span style="color: #CC0000;">11</span><span style="color: #339933;">,</span>
        <span style="color: #3366CC;">&quot;allPlans&quot;</span> <span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span>
                <span style="color: #009900;">&#123;</span>
                        <span style="color: #3366CC;">&quot;cursor&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;BasicCursor&quot;</span><span style="color: #339933;">,</span>
                        <span style="color: #3366CC;">&quot;startKey&quot;</span> <span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span>
&nbsp;
                        <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
                        <span style="color: #3366CC;">&quot;endKey&quot;</span> <span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span>
&nbsp;
                        <span style="color: #009900;">&#125;</span>
                <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#93;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>- yielding some info about the execution of the query. I don&#8217;t know exactly how to interpret all this, but I think I get that <code>"nscanned": 10000</code> means 10000 documents were scanned &#8211; and in a collection with 10000 documents, that&#8217;s not entirely optimal as it implies a full table scan. Now, let&#8217;s make sure that our query will execute as fast as possible by creating and index on the field (<code>_id</code> is always automatically indexed):</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">db.<span style="color: #660066;">posts</span>.<span style="color: #660066;">ensureIndex</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>slug<span style="color: #339933;">:</span><span style="color: #CC0000;">1</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span></pre></div></div>

<p>Now lets <code>explain()</code> again:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&gt;</span> db.<span style="color: #660066;">posts</span>.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>slug<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;post-no-454&quot;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">explain</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
        <span style="color: #3366CC;">&quot;cursor&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;BtreeCursor slug_1&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #3366CC;">&quot;startKey&quot;</span> <span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #3366CC;">&quot;slug&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;post-no-454&quot;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
        <span style="color: #3366CC;">&quot;endKey&quot;</span> <span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #3366CC;">&quot;slug&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;post-no-454&quot;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
        <span style="color: #3366CC;">&quot;nscanned&quot;</span> <span style="color: #339933;">:</span> <span style="color: #CC0000;">1</span><span style="color: #339933;">,</span>
        <span style="color: #3366CC;">&quot;n&quot;</span> <span style="color: #339933;">:</span> <span style="color: #CC0000;">1</span><span style="color: #339933;">,</span>
        <span style="color: #3366CC;">&quot;millis&quot;</span> <span style="color: #339933;">:</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span>
        <span style="color: #3366CC;">&quot;allPlans&quot;</span> <span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span>
                <span style="color: #009900;">&#123;</span>
                        <span style="color: #3366CC;">&quot;cursor&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;BtreeCursor slug_1&quot;</span><span style="color: #339933;">,</span>
                        <span style="color: #3366CC;">&quot;startKey&quot;</span> <span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span>
                                <span style="color: #3366CC;">&quot;slug&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;post-no-454&quot;</span>
                        <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
                        <span style="color: #3366CC;">&quot;endKey&quot;</span> <span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span>
                                <span style="color: #3366CC;">&quot;slug&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;post-no-454&quot;</span>
                        <span style="color: #009900;">&#125;</span>
                <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#93;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Wow! That&#8217;s what I call an improvement!</p>
<p>What about posts with a specific tag? First I tried the following snippet, because I learned that the special <code>$where</code> field could be put in a query document to evaluate a predicate server-side:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> niftyPosts <span style="color: #339933;">=</span> db.<span style="color: #660066;">posts</span>.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>$where<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">tags</span> <span style="color: #339933;">!=</span> <span style="color: #003366; font-weight: bold;">null</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">tags</span>.<span style="color: #660066;">indexOf</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;nifty&quot;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">!=</span> <span style="color: #339933;">-</span><span style="color: #CC0000;">1</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span></pre></div></div>

<p>- and this actually works. This syntax is sort of clunky though. Luckily, MongoDB provides a nifty mechanism for arrays that automagically checks if something is contained in it. So my query can be rewritten to this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> niftyPosts <span style="color: #339933;">=</span> db.<span style="color: #660066;">posts</span>.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>tags<span style="color: #339933;">:</span> <span style="color: #3366CC;">'nifty'</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span></pre></div></div>

<p>Nifty!</p>
<p>Now, to take advantage of indexes, the special query document fields should be used. I showed <code>$where</code> above, but there are more &#8211; to name a few: <code>$gt</code> (greater than), <code>$gte</code> (greater than or equal), <code>$lt</code> (less than), <code>$lte</code> (less than or equal), <code>$ne</code> (not equal), and many more. For example, to count the number of non-nifty posts in February 2010:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&gt;</span> db.<span style="color: #660066;">posts</span>.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
    date<span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span>$gte<span style="color: #339933;">:</span> <span style="color: #CC0000;">20100201</span><span style="color: #339933;">,</span> $lt<span style="color: #339933;">:</span> <span style="color: #CC0000;">20100301</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
    tags<span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span>$ne<span style="color: #339933;">:</span> <span style="color: #3366CC;">'nifty'</span><span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">count</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #CC0000;">0</span></pre></div></div>

<p>Check out <a href="http://www.mongodb.org/display/DOCS/Advanced+Queries">the manual</a> for some great documentation on available operators.</p>
<h4>Conclusion</h4>
<p>Querying with MongoDB actually seems pretty cool and flexible. I like the idea that it&#8217;s possible to execute ad-hoc queries, and for most usage I think the supplied operators are adequate. The ability to supply a predicate function via <code>$where</code> seems really cool, but it should probably only be used in conjunction with one or more of the other operators to avoid a full table scan.</p>
]]></content:encoded>
			<wfw:commentRss>http://mookid.dk/oncode/archives/1145/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>More checking out MongoDB:&#160;References</title>
		<link>http://mookid.dk/oncode/archives/1107</link>
		<comments>http://mookid.dk/oncode/archives/1107#comments</comments>
		<pubDate>Fri, 05 Mar 2010 09:00:38 +0000</pubDate>
		<dc:creator>mookid</dc:creator>
				<category><![CDATA[mongodb]]></category>
		<category><![CDATA[nifty]]></category>

		<guid isPermaLink="false">http://mookid.dk/oncode/?p=1107</guid>
		<description><![CDATA[This post will touch a little bit on the mechanism used for references, and then a few thoughts on how document-orientation relates to OO.
Now &#8211; if you, like me, are into OO and normalized object models &#8211; the weirdness begins&#8230;.. or maybe not?! (actually, I am not sure yet  )
In an OO world (and [...]]]></description>
			<content:encoded><![CDATA[<p>This post will touch a little bit on the mechanism used for references, and then a few thoughts on how document-orientation relates to OO.</p>
<p>Now &#8211; if you, like me, are into OO and normalized object models &#8211; the weirdness begins&#8230;.. or maybe not?! (actually, I am not sure yet <img src='http://mookid.dk/oncode/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> )</p>
<p>In an OO world (and in a normalized RDB world as well), you reference stuff, thus reducing the amount of redundant information as much as possible. E.g. the names of countries should not be put in a column in your <code>address</code> table, each country should have a row in the countries table, and then be referenced by a <code>countryId</code> in the <code>address</code> table.</p>
<p>In a document-oriented world, you generally embed objects instead of referencing them. This is done for performance reasons, and <em>because there&#8217;s no way to join stuff</em> &#8211; which means that a stored ID/foreign key merely remains free for the client to manually use in additional queries.</p>
<p>When you do need to actually reference another document, use <code>DBRef</code> to create a reference, supplying the collection and the ID as arguments. E.g. like so:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&gt;</span> <span style="color: #003366; font-weight: bold;">var</span> author <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span><span style="color: #000066;">name</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">'joe'</span><span style="color: #009900;">&#125;</span>
<span style="color: #339933;">&gt;</span> db.<span style="color: #660066;">authors</span>.<span style="color: #660066;">save</span><span style="color: #009900;">&#40;</span>author<span style="color: #009900;">&#41;</span>
<span style="color: #339933;">&gt;</span> author
<span style="color: #009900;">&#123;</span> <span style="color: #3366CC;">&quot;name&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;joe&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;_id&quot;</span> <span style="color: #339933;">:</span> ObjectId<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;4b8ed200384e0000000065d8&quot;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#125;</span>
<span style="color: #339933;">&gt;</span> <span style="color: #003366; font-weight: bold;">var</span> post <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>headline<span style="color: #339933;">:</span> <span style="color: #3366CC;">'hello there'</span><span style="color: #339933;">,</span> author<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">new</span> DBRef<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'authors'</span><span style="color: #339933;">,</span> author._id<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#125;</span>
<span style="color: #339933;">&gt;</span> db.<span style="color: #660066;">posts</span>.<span style="color: #660066;">save</span><span style="color: #009900;">&#40;</span>post<span style="color: #009900;">&#41;</span>
<span style="color: #339933;">&gt;</span> post
<span style="color: #009900;">&#123;</span>
        <span style="color: #3366CC;">&quot;headline&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;hello there&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #3366CC;">&quot;author&quot;</span> <span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #3366CC;">&quot;$ref&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;authors&quot;</span><span style="color: #339933;">,</span>
                <span style="color: #3366CC;">&quot;$id&quot;</span> <span style="color: #339933;">:</span> ObjectId<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;4b8ed200384e0000000065d8&quot;</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
        <span style="color: #3366CC;">&quot;_id&quot;</span> <span style="color: #339933;">:</span> ObjectId<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;4b8ed4c8384e0000000065d9&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This way, the reference is represented in a consistent manner which may &#8211; or may not &#8211; be picked up by the driver you are using. The C# driver can create <code>DBRef</code>s and follow them, but you don&#8217;t get to join stuff &#8211; you still need an extra query.</p>
<p>Embedding objects may seem a little clunky at first, but actually this plays nicely with some common OO concepts &#8211; take aggregation, for example: a blog post has an array of comments, each of which makes no sense without an aggregating post &#8211; i.e. comments live and die with their post. That&#8217;s an obvious sign that comments should be embedded in the post. So, instead of:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">posts<span style="color: #339933;">:</span>
<span style="color: #009900;">&#123;</span><span style="color: #3366CC;">'_id'</span><span style="color: #339933;">:</span> ObjectId<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'11223344556677889900aabb'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> headline<span style="color: #339933;">:</span> <span style="color: #3366CC;">'A post'</span><span style="color: #009900;">&#125;</span>
&nbsp;
comments<span style="color: #339933;">:</span>
<span style="color: #009900;">&#123;</span><span style="color: #3366CC;">'_id'</span><span style="color: #339933;">:</span> ObjectId<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'bbaa00112233554477669988'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> text<span style="color: #339933;">:</span> <span style="color: #3366CC;">'hello there'</span><span style="color: #339933;">,</span> post<span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span> <span style="color: #3366CC;">&quot;$ref&quot;</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;posts&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;$id&quot;</span><span style="color: #339933;">:</span> ObjectId<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'11223344556677889900aabb'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span><span style="color: #3366CC;">'_id'</span><span style="color: #339933;">:</span> ObjectId<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'881122335544776699aa00bb'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> text<span style="color: #339933;">:</span> <span style="color: #3366CC;">'hello again'</span><span style="color: #339933;">,</span> post<span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span> <span style="color: #3366CC;">&quot;$ref&quot;</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;posts&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;$id&quot;</span><span style="color: #339933;">:</span> ObjectId<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'11223344556677889900aabb'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#125;</span></pre></div></div>

<p>- you should do this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#123;</span>
    <span style="color: #3366CC;">'_id'</span><span style="color: #339933;">:</span> ObjectId<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'11223344556677889900aabb'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> 
    headline<span style="color: #339933;">:</span> <span style="color: #3366CC;">'A post'</span><span style="color: #339933;">,</span>
    comments<span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span>
        <span style="color: #009900;">&#123;</span>text<span style="color: #339933;">:</span> <span style="color: #3366CC;">'hello there'</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
        <span style="color: #009900;">&#123;</span>text<span style="color: #339933;">:</span> <span style="color: #3366CC;">'hello again'</span><span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#93;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Actually this makes me think about the concept of an aggregate root in DDD: an aggregate root &#8220;owns&#8221; the data beneath it, and is responsible for maintaining its own integrity. If you were to delete an aggregate root, all the data beneath it would dissappear.</p>
<p>This also fits kind of nicely with the fact that there&#8217;s no database transactions in MongoDB &#8211; i.e. there&#8217;s no way to issue multiple statements and have them rolled back in case of an error &#8211; there&#8217;s only documents, and either a document gets inserted/updated/deleted, or it doesn&#8217;t. So obviously, the document is the unit of atomicity, which fits (sort of nicely) with the aggregate root and its responsibility of keeping itself internally consistent.</p>
<h4>Conclusion</h4>
<p>The observations stated here pretty much make a document an aggregate root in the DDD sense &#8211; especially since only documents get an <code>_id</code>. There&#8217;s no obvious way to reference a particular comment <em>inside</em> the second post shown above.</p>
<p>If MongoDB&#8217;s performance is up to the task, data should probably be aggregated as much as possible into large documents. MongoDB&#8217;s limit is 4 MB per document, but I am unsure of how large documents should be before you should consider splitting them. </p>
<p>Maybe I am thinking too much about these things? Maybe I should just try and build something and see where my document modeling goes? Suggestions and comments are welcome <img src='http://mookid.dk/oncode/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://mookid.dk/oncode/archives/1107/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Checking out&#160;MongoDB</title>
		<link>http://mookid.dk/oncode/archives/1057</link>
		<comments>http://mookid.dk/oncode/archives/1057#comments</comments>
		<pubDate>Wed, 03 Mar 2010 14:04:21 +0000</pubDate>
		<dc:creator>mookid</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[nifty]]></category>
		<category><![CDATA[nosql]]></category>

		<guid isPermaLink="false">http://mookid.dk/oncode/?p=1057</guid>
		<description><![CDATA[Having experienced a lot of pain using RDBMSs (1) as a default choice of persistence,  having read a couple of blog posts about MongoDB, and being generally interested in widening my horizon, I decided to check out MongoDB. 
This post is a write-as-I-go summary of the information I have gathered from the following places:

MongoDB [...]]]></description>
			<content:encoded><![CDATA[<p>Having experienced a lot of pain using RDBMSs (<sup class='footnote'><a href='#fn-1057-1' id='fnref-1057-1'>1</a></sup>) as a default choice of persistence,  having read a couple of blog posts about MongoDB, and being generally interested in widening my horizon, I decided to check out MongoDB. </p>
<p>This post is a write-as-I-go summary of the information I have gathered from the following places:</p>
<ul>
<li><a href="http://www.mongodb.org/display/DOCS/Manual">MongoDB Manual</a></li>
<li><a href="http://www.mongodb.org/display/DOCS/C+Sharp+Language+Center">MongoDB C# Language Center</a>
<li><a href="http://odetocode.com/Blogs/scott/archive/2009/10/13/experimenting-with-mongodb-from-c.aspx">K. Scott Allen: Experimenting with MongoDB from C#</a></li>
</ul>
<p>More posts may follow&#8230;. <img src='http://mookid.dk/oncode/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h4>Getting MongoDB</h4>
<p>Piece of cake! Download MongoDB from the <a href="http://www.mongodb.org/display/DOCS/Downloads">download center</a> and shove the binaries away somewhere on your machine. Default is for MongoDB to store its data in <code>/data/db</code> which translates to <code>c:\data\db</code> if you are using Windows &#8211; go ahead and create this directory. The MongoDB daemon can be started by running <code>mongod.exe</code>, which will accept connections on <code>localhost:27017</code>.</p>
<p>It will probably look something like the screenshot shown below.</p>
<p><a href="http://mookid.dk/oncode/wp-content/2010/03/mongo-1.png"><img src="http://mookid.dk/oncode/wp-content/2010/03/mongo-1.png" alt="" title="mongod.exe" width="677" height="342" class="aligncenter size-full wp-image-1064" /></a></p>
<p>An alternative data path can be specified on the command line, e.g. like so: <code>mongod --dbpath c:\somewhere\else</code>.</p>
<h4>Accessing it with JavaScript</h4>
<p>Run <code>mongo.exe</code> to start the Mongo Shell. It will probably look something like this:</p>
<p><a href="http://mookid.dk/oncode/wp-content/2010/03/mongo-2.png"><img src="http://mookid.dk/oncode/wp-content/2010/03/mongo-2.png" alt="" title="mongo.exe" width="677" height="342" class="aligncenter size-full wp-image-1065" /></a></p>
<p>In the MongoDB prompt, you can use JavaScript to access the db. Here&#8217;s a sample session of some commands I have found useful:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// lists the dbs in this mongo</span>
<span style="color: #339933;">&gt;</span> show dbs   
admin
local
<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&gt;</span> <span style="color: #006600; font-style: italic;">// change database context to some db (&quot;myblog&quot; - will automagically be created)</span>
<span style="color: #339933;">&gt;</span> <span style="color: #003366; font-weight: bold;">use</span> myblog   
switched to db myblog
<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&gt;</span> show collections
system.<span style="color: #660066;">indexes</span>
<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&gt;</span> <span style="color: #006600; font-style: italic;">// save a couple of documents in a collection named &quot;posts&quot;</span>
<span style="color: #339933;">&gt;</span> <span style="color: #006600; font-style: italic;">// (collection will be automagically created as well...)</span>
<span style="color: #339933;">&gt;</span> db.<span style="color: #660066;">posts</span>.<span style="color: #660066;">save</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
    headline<span style="color: #339933;">:</span> <span style="color: #3366CC;">'Notes to self about MongoDB'</span><span style="color: #339933;">,</span> 
    slug<span style="color: #339933;">:</span> <span style="color: #3366CC;">'notes-to-self-about-mongodb'</span><span style="color: #339933;">,</span> 
    tags<span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span><span style="color: #3366CC;">'mongodb'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'nosql'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'nifty'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'c#'</span><span style="color: #009900;">&#93;</span>
 <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>
<span style="color: #339933;">&gt;</span> db.<span style="color: #660066;">posts</span>.<span style="color: #660066;">save</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
    headline<span style="color: #339933;">:</span> <span style="color: #3366CC;">'Someday I want to check out CouchDB as well'</span><span style="color: #339933;">,</span> 
    slug<span style="color: #339933;">:</span> <span style="color: #3366CC;">'someday-i-want-to-check-out-couchdb-as-well'</span><span style="color: #339933;">,</span> 
    tags<span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span><span style="color: #3366CC;">'couchdb'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'nosql'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'nifty'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'c#'</span><span style="color: #009900;">&#93;</span>
 <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>
<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&gt;</span> <span style="color: #006600; font-style: italic;">// show documents in a collection (returns a cursor, which will be iterated for the first 10 or 20 results - next pages can be retrieved with the 'it' command)</span>
<span style="color: #339933;">&gt;</span> db.<span style="color: #660066;">posts</span>.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span> <span style="color: #3366CC;">&quot;_id&quot;</span> <span style="color: #339933;">:</span> ObjectId<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;4b8e4281781b000000005cfc&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;headline&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Notes to self about MongoDB&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;slug&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;notes-to-self-about-mongodb&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;tags&quot;</span> <span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span> <span style="color: #3366CC;">&quot;mongodb&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;nosql&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;nifty&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;c#&quot;</span> <span style="color: #009900;">&#93;</span> <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span> <span style="color: #3366CC;">&quot;_id&quot;</span> <span style="color: #339933;">:</span> ObjectId<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;4b8e42cc781b000000005cfd&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;headline&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Someday I want to check out CouchDB as well&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;slug&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;someday-i-want-to-check-out-couchdb-as-well&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;tags&quot;</span> <span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span> <span style="color: #3366CC;">&quot;couchdb&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;nosql&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;nifty&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;c#&quot;</span> <span style="color: #009900;">&#93;</span> <span style="color: #009900;">&#125;</span></pre></div></div>

<p>Now, I have successfully added two documents representing blog posts in a collection named <code>posts</code>. As you can see, MongoDB assigns some funky IDs to the documents.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&gt;</span> <span style="color: #006600; font-style: italic;">// lets get the first post ('find' and 'findOne' accept a query document as their first parameter)</span>
<span style="color: #339933;">&gt;</span> db.<span style="color: #660066;">posts</span>.<span style="color: #660066;">findOne</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span><span style="color: #3366CC;">'_id'</span><span style="color: #339933;">:</span> ObjectId<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'4b8e4281781b000000005cfc'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
        <span style="color: #3366CC;">&quot;_id&quot;</span> <span style="color: #339933;">:</span> ObjectId<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;4b8e4281781b000000005cfc&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
        <span style="color: #3366CC;">&quot;headline&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Notes to self about MongoDB&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #3366CC;">&quot;slug&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;notes-to-self-about-mongodb&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #3366CC;">&quot;tags&quot;</span> <span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span>
                <span style="color: #3366CC;">&quot;mongodb&quot;</span><span style="color: #339933;">,</span>
                <span style="color: #3366CC;">&quot;nosql&quot;</span><span style="color: #339933;">,</span>
                <span style="color: #3366CC;">&quot;nifty&quot;</span><span style="color: #339933;">,</span>
                <span style="color: #3366CC;">&quot;c#&quot;</span>
        <span style="color: #009900;">&#93;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&gt;</span> <span style="color: #006600; font-style: italic;">// now let's find all IDs ('find' and 'findOne' accept as their second parameter a document</span>
<span style="color: #339933;">&gt;</span> <span style="color: #006600; font-style: italic;">// specifying which fields to return)</span>
<span style="color: #339933;">&gt;</span> db.<span style="color: #660066;">posts</span>.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#123;</span><span style="color: #3366CC;">'_id'</span><span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">true</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span> <span style="color: #3366CC;">&quot;_id&quot;</span> <span style="color: #339933;">:</span> ObjectId<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;4b8e4281781b000000005cfc&quot;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span> <span style="color: #3366CC;">&quot;_id&quot;</span> <span style="color: #339933;">:</span> ObjectId<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;4b8e42cc781b000000005cfd&quot;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span> <span style="color: #3366CC;">&quot;_id&quot;</span> <span style="color: #339933;">:</span> ObjectId<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;4b8e4595781b000000005cfe&quot;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#125;</span>
<span style="color: #339933;">&gt;</span></pre></div></div>

<p>That was a brief demonstration of the JavaScript API in the Mongo Shell. Now, let&#8217;s do this from C#.</p>
<h4>Getting started with mongodb-csharp</h4>
<p>Now, go to <a href="http://github.com/samus/mongodb-csharp/downloads">mongodb-csharp dowload section at GitHub</a> and get a debug build of the driver. Create a C# project and reference the <code>MongoDB.Driver</code> assembly.</p>
<p>On my machine, punching in the following actually works:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>Test<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> CanAddPost<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">using</span><span style="color: #000000;">&#40;</span>var mongo <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Mongo<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
  <span style="color: #000000;">&#123;</span>
    mongo.<span style="color: #0000FF;">Connect</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    var db <span style="color: #008000;">=</span> mongo<span style="color: #000000;">&#91;</span><span style="color: #666666;">&quot;myblog&quot;</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
    var posts <span style="color: #008000;">=</span> db<span style="color: #000000;">&#91;</span><span style="color: #666666;">&quot;posts&quot;</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
&nbsp;
    posts.<span style="color: #0000FF;">Insert</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> Document
                   <span style="color: #000000;">&#123;</span>
                     <span style="color: #000000;">&#123;</span><span style="color: #666666;">&quot;headline&quot;</span>, <span style="color: #666666;">&quot;Post added from C#&quot;</span><span style="color: #000000;">&#125;</span>,
                     <span style="color: #000000;">&#123;</span><span style="color: #666666;">&quot;slug&quot;</span>, <span style="color: #666666;">&quot;post-added-from-csharp&quot;</span><span style="color: #000000;">&#125;</span>,
                     <span style="color: #000000;">&#123;</span>
                       <span style="color: #666666;">&quot;tags&quot;</span>, <span style="color: #008000;">new</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span>
                                 <span style="color: #000000;">&#123;</span>
                                   <span style="color: #666666;">&quot;c#&quot;</span>,
                                   <span style="color: #666666;">&quot;nifty&quot;</span>
                                 <span style="color: #000000;">&#125;</span>
                       <span style="color: #000000;">&#125;</span>
                   <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Now, I can verify that the document is actually in there by going back to the console and doing this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&gt;</span> db.<span style="color: #660066;">posts</span>.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span> <span style="color: #3366CC;">&quot;_id&quot;</span> <span style="color: #339933;">:</span> ObjectId<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;4b8e4281781b000000005cfc&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;headline&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Notes to self about MongoDB&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;slug&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;notes-to-self-about-mongodb&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;tags&quot;</span> <span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span> <span style="color: #3366CC;">&quot;mongodb&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;nosql&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;nifty&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;c#&quot;</span> <span style="color: #009900;">&#93;</span> <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span> <span style="color: #3366CC;">&quot;_id&quot;</span> <span style="color: #339933;">:</span> ObjectId<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;4b8e42cc781b000000005cfd&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;headline&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Someday I want to check out CouchDB as well&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;slug&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;someday-i-want-to-check-out-couchdb-as-well&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;tags&quot;</span> <span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span> <span style="color: #3366CC;">&quot;couchdb&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;nosql&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;nifty&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;c#&quot;</span> <span style="color: #009900;">&#93;</span> <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span> <span style="color: #3366CC;">&quot;_id&quot;</span> <span style="color: #339933;">:</span> ObjectId<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;4b8e4b72091abb14e4000001&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;headline&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Post added from C#&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;slug&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;post-added-from-csharp&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;tags&quot;</span> <span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span> <span style="color: #3366CC;">&quot;c#&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;nifty&quot;</span> <span style="color: #009900;">&#93;</span> <span style="color: #009900;">&#125;</span>
<span style="color: #339933;">&gt;</span></pre></div></div>

<p>Nifty! Now lets show the posts from C#. On my machine the following snippet displays the headlines of all posts:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>Test<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> CanShowPosts<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">using</span><span style="color: #000000;">&#40;</span>var mongo <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Mongo<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
  <span style="color: #000000;">&#123;</span>
    mongo.<span style="color: #0000FF;">Connect</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    var db <span style="color: #008000;">=</span> mongo<span style="color: #000000;">&#91;</span><span style="color: #666666;">&quot;myblog&quot;</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
    var posts <span style="color: #008000;">=</span> db<span style="color: #000000;">&#91;</span><span style="color: #666666;">&quot;posts&quot;</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
&nbsp;
    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Posts&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF;">foreach</span><span style="color: #000000;">&#40;</span>var post <span style="color: #0600FF;">in</span> posts.<span style="color: #0000FF;">FindAll</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Documents</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
      Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;    {0}&quot;</span>, post<span style="color: #000000;">&#91;</span><span style="color: #666666;">&quot;headline&quot;</span><span style="color: #000000;">&#93;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>- which is documented in the following screenshot:</p>
<p><a href="http://mookid.dk/oncode/wp-content/2010/03/mongo-3.png"><img src="http://mookid.dk/oncode/wp-content/2010/03/mongo-3.png" alt="" title="can-show-post-headlines" width="467" height="381" class="aligncenter size-full wp-image-1085" /></a></p>
<h4>Random nuggets of information</h4>
<h5>Document IDs</h5>
<p>All MongoDB documents must have an ID in the <code>_id</code> field, either assigned by you (any object can be used), or automatically by MongoDB. IDs generated by MongoDB are virtually globally unique, as they consist of the following: 4 bytes of timestamp, 3 bytes of machine identification, 2 bytes of process identification, 3 bytes of something that gets incremented.</p>
<p>As a nifty consequence, the time of creation can be extracted from auto-generated IDs.</p>
<p>The ID type used by MongoDB can be created with <code>ObjectId('00112233445566778899aabb')</code> (where the input must be a string representing 12 bytes in HEX).</p>
<h5>How are documents stored?</h5>
<p>I you have not yet figured it out, documents are serialized to JSON &#8211; with the minor modification that it&#8217;s a BINARY version of JSON, hence it&#8217;s called BSON.</p>
<h5>String encoding</h5>
<p>UTF-8. No worries.</p>
<h5>What about references?</h5>
<p>I will research this and do a separate post on the subject. As MongoDB is non-relational, a &#8220;join&#8221; is &#8211; in principle &#8211; an unknown concept. There&#8217;s a mechanism, however, that allows for consistent representation of foreign keys that may/may not give you some extra functionality (depending on the driver you are using).</p>
<h5>What about querying?</h5>
<p>I will research this as well, posting as I go.</p>
<h5>OR/M? (or OD/M?)</h5>
<p>It is not yet clear to me how to handle Object-Document Mapping. Will require some research as well. As an OO dude, I am especially interested in finding out what a schema-less persistance mechanism will do to my design.</p>
<h5>What else?</h5>
<p>More topics include applying indices, deleting/updating, atomicity, and more. Implies additional blog posts.</p>
<h4>Conclusion</h4>
<p>My first impression of MongoDB is really good. It&#8217;s <em>extremely easy</em> to get going, and the few error messages I have received were easy to understand.</p>
<p>I am especially in awe with how little friction I encountered &#8211; mostly because of the schema-less nature, but also because everything just worked right away.
<div class='footnotes'>
<div class='footnotedivider'></div>
<ol>
<li id='fn-1057-1'>Usually because of <em>ab</em>using RDBMSs, actually. Storing an object model in a RDBMS is not painful as long as the tooling is right &#8211; e.g. by leveraging the amazing NHibernate. The pain comes when developers suddenly start implementing overly complex queries and <em>doing reporting</em> on top of a pretty entity model, modeling stuff OO style&#8230; ouch! <span class='footnotereverse'><a href='#fnref-1057-1'>&#8617;</a></span></li>
</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://mookid.dk/oncode/archives/1057/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>NHibernate is very&#160;flexible</title>
		<link>http://mookid.dk/oncode/archives/991</link>
		<comments>http://mookid.dk/oncode/archives/991#comments</comments>
		<pubDate>Fri, 29 Jan 2010 07:04:30 +0000</pubDate>
		<dc:creator>mookid</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[lambda]]></category>
		<category><![CDATA[nhibernate]]></category>
		<category><![CDATA[nifty]]></category>
		<category><![CDATA[snippet]]></category>

		<guid isPermaLink="false">http://mookid.dk/oncode/?p=991</guid>
		<description><![CDATA[&#8230;but it does impose limitations on your domain model. 
Most of these limitations, however, like the need for public/internal/protected members to be virtual, and the requirement for a default constructor to exist with at least protected accessibility, are not that hard to adhere to and usually don&#8217;t interfere with what you would do if there [...]]]></description>
			<content:encoded><![CDATA[<p>&#8230;but it does impose limitations on your domain model. </p>
<p>Most of these limitations, however, like the need for <code>public</code>/<code>internal</code>/<code>protected</code> members to be <code>virtual</code>, and the requirement for a default constructor to exist with at least <code>protected</code> accessibility, are not that hard to adhere to and usually don&#8217;t interfere with what you would do if there were no rules at all.</p>
<p>One of the limitations, however, <em>can</em> be pretty significant &#8211; Ayende describes the problem <a href="http://ayende.com/Blog/archive/2010/01/09/nhibernate-polymorphic-associations-and-ghost-objects.aspx">here</a>, using the term &#8220;ghost objects&#8221;.</p>
<p>But, as I am about to show, this significance only arises if you follow a certain style of coding, which you should usually avoid!</p>
<h5>Short explanation of the problem</h5>
<p><a href="http://mookid.dk/oncode/wp-content/2010/01/proxy.jpg"><img src="http://mookid.dk/oncode/wp-content/2010/01/proxy.jpg" alt="" title="proxy" width="395" height="162" class="alignright size-full wp-image-1034" /></a>When NHibernate lazy-loads an entity from the db (i.e. when you call <code>session.Load&lt;TEntity&gt;(id)</code> or when an entity in your session references something through a lazy-loaded association), it does so by providing an instance of a runtime-generated type, which acts as a proxy.</p>
<p>The first time you access something on the proxy, it gets &#8220;hydrated&#8221;, which is just a fancy way of saying that the data will be loaded from the database.</p>
<p>This would be fine and dandy, if it weren&#8217;t for the fact that the proxy is a <em>runtime-generated subclass of your entity</em>, which &#8211; in cases where inheritance is involved &#8211; will be a sibling to the other derived classes. Consider the simple inheritance hierarchy on the sketch to the right which in code could be something like so:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> abstract <span style="color: #FF0000;">class</span> LegalEntity
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">virtual</span> Guid Id <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Person <span style="color: #008000;">:</span> LegalEntity
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">virtual</span> <span style="color: #FF0000;">string</span> FirstNames <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">virtual</span> <span style="color: #FF0000;">string</span> LastName <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Company <span style="color: #008000;">:</span> LegalEntity
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">virtual</span> <span style="color: #FF0000;">string</span> CompanyName <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>- and then NHibernate will generate something along the lines of this (fake <img src='http://mookid.dk/oncode/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ) class signature:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> LegalEntityProxy1234AndSomeMoreStuff <span style="color: #008000;">:</span> LegalEntity
<span style="color: #000000;">&#123;</span>
   <span style="color: #008080; font-style: italic;">// ... secret stuff to access db in here</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>See the problem? Here&#8217;s the problem:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var legalEntity <span style="color: #008000;">=</span> session.<span style="color: #0000FF;">Load</span><span style="color: #008000;">&lt;</span>LegalEntity<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>someKnownId<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
Assert.<span style="color: #0000FF;">IsTrue</span><span style="color: #000000;">&#40;</span>legalEntity <span style="color: #008000;">is</span> Person
              <span style="color: #008000;">||</span> legalEntity <span style="color: #008000;">is</span> Company<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>  <span style="color: #008080; font-style: italic;">//&lt; AssertionException! will never be Person or Company</span></pre></div></div>

<p>This means that this kind of runtime type checking will fail in those circumstances where the entity is a lazy-loaded reference of the supertype, and the following will FAIL:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var legalEntity <span style="color: #008000;">=</span> session.<span style="color: #0000FF;">Load</span><span style="color: #008000;">&lt;</span>LegalEntity<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>someKnownId<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>legalEntity <span style="color: #008000;">is</span> Person<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    var person <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span>Person<span style="color: #000000;">&#41;</span> legalEntity<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">return</span> person.<span style="color: #0000FF;">FirstNames</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot; &quot;</span> <span style="color: #008000;">+</span> person.<span style="color: #0000FF;">LastName</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF;">else</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// we know it's a company then, right? WRONG!</span>
    var company <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span>Company<span style="color: #000000;">&#41;</span> legalEntity<span style="color: #008000;">;</span>  <span style="color: #008080; font-style: italic;">//&lt; InvalidCastException!</span>
    <span style="color: #0600FF;">return</span> company.<span style="color: #0000FF;">CompanyName</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<h5>One possible solution</h5>
<p>The other day, Ayende blogged about <a href="http://ayende.com/Blog/archive/2010/01/27/nhibernate-new-feature-lazy-properties.aspx">a recent addition</a> to NHibernate, namely <em>lazy-loaded properties</em>. This allows an entity to be partially hydrated, intercepting calls to certain properties to lazy-load the relevant fields on demand.</p>
<p>This feature is great when storing LOBs alongside the other fields on an entity, but it also laid the ground for <a href="http://ayende.com/Blog/archive/2010/01/28/nhibernate-new-feature-no-proxy-associations.aspx">his most recent addition</a>, which is the ability to lazy-load an association by setting <code>lazy="no-proxy"</code> on it.</p>
<p>This way, NHibernate will not build a proxy, but instead it will intercept the property getter and load the entity at that point in time, thus being able to return the exact (sub)type of the loaded entity.</p>
<p>Now this seems to solve our problems, but let&#8217;s zoom out a bit &#8230; why did we have a problem in the first place? Our problem was actually that we <em>failed to write object-oriented code</em>, but instead we wrote a brittle piece of code that would fail at runtime whenever someone added a new subtype, thus violating the <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle">Liskov substitution principle</a>. Moreover it just feels wrong to implement business logic that reflects on types!</p>
<h5>What to do then?</h5>
<p>Well, how about making your code polymorphic? The logic above could be easily rewritten as:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> abstract <span style="color: #FF0000;">class</span> LegalEntity
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">virtual</span> Guid Id <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> abstract <span style="color: #FF0000;">string</span> Name <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Person <span style="color: #008000;">:</span> LegalEntity
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">virtual</span> <span style="color: #FF0000;">string</span> FirstNames <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">virtual</span> <span style="color: #FF0000;">string</span> LastName <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #FF0000;">string</span> Name
    <span style="color: #000000;">&#123;</span>
        get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> FirstNames <span style="color: #008000;">+</span> <span style="color: #666666;">&quot; &quot;</span> <span style="color: #008000;">+</span> LastName<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Company <span style="color: #008000;">:</span> LegalEntity
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">virtual</span> <span style="color: #FF0000;">string</span> CompanyName <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #FF0000;">string</span> Name
    <span style="color: #000000;">&#123;</span>
        get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> CompanyName<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>- which moves the logic of yielding name as a oneliner into the class hierarchy, allowing us to always get a name from a <code>LegalEntity</code>.</p>
<h5>What if I really really need a concrete instance?</h5>
<p>Then you should use the nifty <a href="http://en.wikipedia.org/wiki/Visitor_pattern">visitor pattern</a> to extract what you need. In the example above, I would need to add the following additions:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">interface</span> ILegalEntityVisitor
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">void</span> Visit<span style="color: #000000;">&#40;</span>Person person<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF;">void</span> Visit<span style="color: #000000;">&#40;</span>Company company<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">public</span> abstract <span style="color: #FF0000;">class</span> LegalEntity
<span style="color: #000000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// ...</span>
&nbsp;
    <span style="color: #0600FF;">public</span> abstract <span style="color: #0600FF;">void</span> Accept<span style="color: #000000;">&#40;</span>ILegalEntityVisitor visitor<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Person <span style="color: #008000;">:</span> LegalEntity
<span style="color: #000000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// ...</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #0600FF;">void</span> Accept<span style="color: #000000;">&#40;</span>ILegalEntityVisitor visitor<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        visitor.<span style="color: #0000FF;">Visit</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;">this</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Company <span style="color: #008000;">:</span> LegalEntity
<span style="color: #000000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// ...</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #0600FF;">void</span> Accept<span style="color: #000000;">&#40;</span>ILegalEntityVisitor visitor<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        visitor.<span style="color: #0000FF;">Visit</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;">this</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>This way, we&#8217;re taking advantage of the fact the each subclass knows its own concrete instance, thus allowing it to pass itself to the visitor we passed in.</p>
<p>This is the preferred solution when the logic you&#8217;re writing doesn&#8217;t belong inside the actual entitiy class, like e.g. when you want to convert the entity to an editable view object, because this will make your code break at compile time if someone adds a new specialization, thus requiring each piece of logic to handle that specialization as well.</p>
<p>Oh, and if you&#8217;re a Java guy, you might be missing the ability to create an inline anonymous visitor within the scope of the current method, but that can be easily emulated by a <em>generic visitor</em>, like so:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> LegalEntityVisitor <span style="color: #008000;">:</span> ILegalEntityVisitor
<span style="color: #000000;">&#123;</span>
    Action<span style="color: #008000;">&lt;</span>Person<span style="color: #008000;">&gt;</span> handlePerson<span style="color: #008000;">;</span>
    Action<span style="color: #008000;">&lt;</span>Company<span style="color: #008000;">&gt;</span> handleCompany<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> LegalEntityVisitor<span style="color: #000000;">&#40;</span>Action<span style="color: #008000;">&lt;</span>Person<span style="color: #008000;">&gt;</span> handlePerson, Action<span style="color: #008000;">&lt;</span>Company<span style="color: #008000;">&gt;</span> handleCompany<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">handlePerson</span> <span style="color: #008000;">=</span> handlePerson<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">handleCompany</span> <span style="color: #008000;">=</span> handleCompany<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Visit<span style="color: #000000;">&#40;</span>Person person<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        handlePerson<span style="color: #000000;">&#40;</span>person<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Visit<span style="color: #000000;">&#40;</span>Company company<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        handleCompany<span style="color: #000000;">&#40;</span>company<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>- which would allow you to write inline typesafe code like this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #FF0000;">double</span> risk <span style="color: #008000;">=</span> CalculateInitialRisk<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// multiply some number depending on type of legal entity</span>
legalEntity.<span style="color: #0000FF;">Visit</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> LegalEntityVisitor<span style="color: #000000;">&#40;</span>person <span style="color: #008000;">=&gt;</span> risk <span style="color: #008000;">*=</span> GetRiskExperienceForPeople<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>,
                                         company <span style="color: #008000;">=&gt;</span> risk <span style="color: #008000;">*=</span> GetRiskExperienceForCompany<span style="color: #000000;">&#40;</span>company<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Only thing missing now is the ability to return a value in one line depending on the subclass. Well, the generic visitor can be used for that as well by adding the following:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> LegalEntityVisitor <span style="color: #008000;">:</span> ILegalEntityVisitor
<span style="color: #000000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// ...</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> TResult Func<span style="color: #008000;">&lt;</span>TResult<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>LegalEntity legalEntity, 
                                        Func<span style="color: #008000;">&lt;</span>Person, TResult<span style="color: #008000;">&gt;</span> handlePerson, 
                                        Func<span style="color: #008000;">&lt;</span>Company, TResult<span style="color: #008000;">&gt;</span> handleCompany<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        TResult result <span style="color: #008000;">=</span> <span style="color: #0600FF;">default</span><span style="color: #000000;">&#40;</span>TResult<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        legalEntity.<span style="color: #0000FF;">Visit</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> LegalEntityVisitor<span style="color: #000000;">&#40;</span>p <span style="color: #008000;">=&gt;</span> result <span style="color: #008000;">=</span> handlePerson<span style="color: #000000;">&#40;</span>p<span style="color: #000000;">&#41;</span>,
                                                 c <span style="color: #008000;">=&gt;</span> result <span style="color: #008000;">=</span> handleCompany<span style="color: #000000;">&#40;</span>c<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF;">return</span> result<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>- allowing you to write code like this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> GetReportTypeCodeFor<span style="color: #000000;">&#40;</span>LegalEntity legalEntity<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">return</span> LegalEntityVisitor.<span style="color: #0000FF;">Func</span><span style="color: #000000;">&#40;</span>legalEntity, p <span style="color: #008000;">=&gt;</span> <span style="color: #666666;">&quot;P00000&quot;</span>, c <span style="color: #008000;">=&gt;</span> <span style="color: #666666;">&quot;C&quot;</span> <span style="color: #008000;">+</span> GetReportingCode<span style="color: #000000;">&#40;</span>c<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>- and still have the benefit of compile-time safety that all specializations have been handled.</p>
<h5>When to reflect on types?</h5>
<p>IMO you should only reflect on types in business logic when it&#8217;s a shortcut that <em>doesn&#8217;t break the semantics of your code</em>. What do I mean by that? Well, e.g. the implementation of the extension method <code>System.Linq.Enumerable.Count<T>()</code> looks something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> Count<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;">this</span> IEnumerale<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span> items<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>items <span style="color: #008000;">is</span> ICollection<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">return</span> <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>ICollection<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#41;</span>items<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Count</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    var count <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
    <span style="color: #008080; font-style: italic;">// iterate and count manually</span>
&nbsp;
    <span style="color: #0600FF;">return</span> count<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>This way, providing the number of items is accelerated for certain implementations of <code>IEnumerable&lt;T&gt;</code> because the information is already there, and for other types there&#8217;s no way to avoid manually counting.</p>
<h5>Conclusion</h5>
<p>I don&#8217;t think I will be using the new <code>lazy="no-proxy"</code> feature, because if I need it, I think it is a sign that my design has a bad smell to it, and I should either go for polymorphism or using a visitor.</p>
]]></content:encoded>
			<wfw:commentRss>http://mookid.dk/oncode/archives/991/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>When jQuery was&#160;released&#8230;</title>
		<link>http://mookid.dk/oncode/archives/982</link>
		<comments>http://mookid.dk/oncode/archives/982#comments</comments>
		<pubDate>Fri, 15 Jan 2010 08:33:34 +0000</pubDate>
		<dc:creator>mookid</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://mookid.dk/oncode/?p=982</guid>
		<description><![CDATA[&#8230;web development changed forever! (to me at least  )
It&#8217;s amazing how the CSS-selector-based approach has proven its effectiveness and durability, and combined with the incredible wealth of extensions, choosing jQuery is simply a no-brainer.
By the way, jQuery 1.4 has been released. Check out this post for a walkthrough of some of the new features.
]]></description>
			<content:encoded><![CDATA[<p>&#8230;web development changed forever! (to me at least <img src='http://mookid.dk/oncode/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> )</p>
<p>It&#8217;s amazing how the CSS-selector-based approach has proven its effectiveness and durability, and combined with the incredible wealth of extensions, choosing jQuery is simply a no-brainer.</p>
<p>By the way, <a href="http://jquery14.com/">jQuery 1.4 has been released</a>. Check out <a href="http://net.tutsplus.com/tutorials/javascript-ajax/jquery-1-4-released-the-15-new-features-you-must-know/">this post</a> for a walkthrough of some of the new features.</p>
]]></content:encoded>
			<wfw:commentRss>http://mookid.dk/oncode/archives/982/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C# vs. Clojure vs. Ruby &amp;&#160;Scala</title>
		<link>http://mookid.dk/oncode/archives/950</link>
		<comments>http://mookid.dk/oncode/archives/950#comments</comments>
		<pubDate>Wed, 06 Jan 2010 20:00:23 +0000</pubDate>
		<dc:creator>mookid</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[snippet]]></category>

		<guid isPermaLink="false">http://mookid.dk/oncode/?p=950</guid>
		<description><![CDATA[Short preface: at a job interview, Zach Cox was told to aggregate words and word counts from a bunch of files into two files, sorted alphabetically and by word count respectively, which he did in Ruby and Scala. This led Lau Bjørn Jensen to do the same thing in Clojure, which apparantly sparked other people [...]]]></description>
			<content:encoded><![CDATA[<p><em>Short preface</em>: at a job interview, Zach Cox was told to aggregate words and word counts from a bunch of files into two files, sorted alphabetically and by word count respectively, which <a href="http://blogs.sourceallies.com/2009/12/word-counts-example-in-ruby-and-scala/">he did in Ruby and Scala</a>. This led Lau Bjørn Jensen to <a href="http://www.bestinclass.dk/index.php/2009/12/clojure-vs-ruby-scala-transient-newsgroups">do the same thing in Clojure</a>, which apparantly sparked other people to do it in Java, Python etc.</p>
<p>Inspired by the aforementioned problem, and an extended train ride home (thank you, Danish National Railways!!), I decided to see what a C# (v. 3) version could look like:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">namespace</span> NewsReader
<span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
  <span style="color: #0600FF;">using</span> <span style="color: #008080;">System.IO</span><span style="color: #008000;">;</span>
  <span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Linq</span><span style="color: #008000;">;</span>
  <span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Text.RegularExpressions</span><span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #FF0000;">class</span> Program
  <span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
      <span style="color: #0600FF;">const</span> <span style="color: #FF0000;">string</span> dir <span style="color: #008000;">=</span> <span style="color: #666666;">@&quot;c:\temp\20_newsgroups&quot;</span><span style="color: #008000;">;</span>
      var stopwatch <span style="color: #008000;">=</span> <span style="color: #000000;">System.<span style="color: #0000FF;">Diagnostics</span></span>.<span style="color: #0000FF;">Stopwatch</span>.<span style="color: #0000FF;">StartNew</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
      var regex <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Regex<span style="color: #000000;">&#40;</span><span style="color: #666666;">@&quot;\w+&quot;</span>, RegexOptions.<span style="color: #0000FF;">Compiled</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
      var list <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span>from filename <span style="color: #0600FF;">in</span> Directory.<span style="color: #0000FF;">GetFiles</span><span style="color: #000000;">&#40;</span>dir, <span style="color: #666666;">&quot;*.*&quot;</span>, SearchOption.<span style="color: #0000FF;">AllDirectories</span><span style="color: #000000;">&#41;</span>
                  from match <span style="color: #0600FF;">in</span> regex.<span style="color: #0000FF;">Matches</span><span style="color: #000000;">&#40;</span>File.<span style="color: #0000FF;">ReadAllText</span><span style="color: #000000;">&#40;</span>filename<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ToLower</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Cast</span><span style="color: #008000;">&lt;</span>Match<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
                  let word <span style="color: #008000;">=</span> match.<span style="color: #0000FF;">Value</span>
                  group word by word
                  into aggregate
                    select <span style="color: #008000;">new</span>
                             <span style="color: #000000;">&#123;</span>
                               Word <span style="color: #008000;">=</span> aggregate.<span style="color: #0000FF;">Key</span>,
                               Count <span style="color: #008000;">=</span> aggregate.<span style="color: #0000FF;">Count</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>  ,
                               Text <span style="color: #008000;">=</span> <span style="color: #FF0000;">string</span>.<span style="color: #0000FF;">Format</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;{0}<span style="color: #008080; font-weight: bold;">\t</span>{1}&quot;</span>, aggregate.<span style="color: #0000FF;">Key</span>, aggregate.<span style="color: #0000FF;">Count</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                             <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>
        .<span style="color: #0000FF;">ToList</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
      File.<span style="color: #0000FF;">WriteAllLines</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">@&quot;c:\temp\words-ordered-by-count.txt&quot;</span>, list.<span style="color: #0000FF;">OrderBy</span><span style="color: #000000;">&#40;</span>c <span style="color: #008000;">=&gt;</span> c.<span style="color: #0000FF;">Count</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Select</span><span style="color: #000000;">&#40;</span>c <span style="color: #008000;">=&gt;</span> c.<span style="color: #0000FF;">Text</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ToArray</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
      File.<span style="color: #0000FF;">WriteAllLines</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">@&quot;c:\temp\words-ordered-by-word.txt&quot;</span>, list.<span style="color: #0000FF;">OrderBy</span><span style="color: #000000;">&#40;</span>c <span style="color: #008000;">=&gt;</span> c.<span style="color: #0000FF;">Word</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Select</span><span style="color: #000000;">&#40;</span>c <span style="color: #008000;">=&gt;</span> c.<span style="color: #0000FF;">Text</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ToArray</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
      Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Elapsed: {0:0.0} seconds&quot;</span>, stopwatch.<span style="color: #0000FF;">Elapsed</span>.<span style="color: #0000FF;">TotalSeconds</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Weighing in at 35 lines and executing in 10.2 seconds (on my Intel Core 2 laptop with 4 GB RAM), I think this is a pretty clear and performant alternative to the other languages mentioned.</p>
]]></content:encoded>
			<wfw:commentRss>http://mookid.dk/oncode/archives/950/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Tomatoday</title>
		<link>http://mookid.dk/oncode/archives/924</link>
		<comments>http://mookid.dk/oncode/archives/924#comments</comments>
		<pubDate>Wed, 30 Dec 2009 14:40:11 +0000</pubDate>
		<dc:creator>mookid</dc:creator>
				<category><![CDATA[nifty]]></category>
		<category><![CDATA[pomodoro]]></category>
		<category><![CDATA[silverlight]]></category>

		<guid isPermaLink="false">http://mookid.dk/oncode/?p=924</guid>
		<description><![CDATA[As mentioned in my previous post, my colleague Troels Richter is working on a Pomodoro application. What I did not say was that it is actually already available for people to try out &#8211; it&#8217;s called Tomatoday, it&#8217;s based on Silverlight 3 (SL4 version on the way), and it can be found at www.tomatoday.dk.
It consists [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://mookid.dk/oncode/wp-content/2009/12/tomatoday.png"><img src="http://mookid.dk/oncode/wp-content/2009/12/tomatoday.png" alt="tomatoday logo" title="tomatoday" width="301" height="62" class="alignright size-full wp-image-929" /></a>As mentioned in my <a href="http://mookid.dk/oncode/archives/861">previous post</a>, my colleague <a href="http://www.blog.troelsrichter.dk/">Troels Richter</a> is working on a <a href="http://www.pomodorotechnique.com/">Pomodoro</a> application. What I did not say was that it is actually already available for people to try out &#8211; it&#8217;s called <strong>Tomatoday</strong>, it&#8217;s based on Silverlight 3 (SL4 version on the way), and it can be found at <a href="http://www.tomatoday.dk">www.tomatoday.dk</a>.</p>
<p>It consists of an online activity inventory and a simple timer application that is pretty nifty when run out-of-browser. It will of course be even niftier when it gets fully ported to Silverlight 4 when the timer gets to run in <em>chrome-less out-of-browser mode</em>.</p>
<p>If you try out the application, and you have suggestions or ideas, we will be very grateful if you submit them to <a href="https://tomatoday.uservoice.com">Tomatoday&#8217;s forum at Uservoice</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://mookid.dk/oncode/archives/924/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Hot tomato&#160;sauce</title>
		<link>http://mookid.dk/oncode/archives/861</link>
		<comments>http://mookid.dk/oncode/archives/861#comments</comments>
		<pubDate>Thu, 03 Dec 2009 09:00:12 +0000</pubDate>
		<dc:creator>mookid</dc:creator>
				<category><![CDATA[nifty]]></category>
		<category><![CDATA[pomodoro]]></category>
		<category><![CDATA[process]]></category>

		<guid isPermaLink="false">http://mookid.dk/oncode/?p=861</guid>
		<description><![CDATA[At Trifork where I work, one of the hot new things is The Pomodoro Technique, as it seems more and more of my colleagues are experimenting with it. If you don&#8217;t know anything about it, I can tell you (in my own words) that it&#8217;s a personal mini-process to make you more productive, thus more [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://mookid.dk/oncode/wp-content/2009/12/pomodoro-technique.png" alt="pomodoro-technique" title="pomodoro-technique" width="207" height="164" class="alignright size-full wp-image-883" />At <a href="http://www.trifork.com/">Trifork</a> where I work, one of the <em>hot new things</em> is <a href="http://www.pomodorotechnique.com/">The Pomodoro Technique</a>, as it seems more and more of my colleagues are experimenting with it. If you don&#8217;t know anything about it, I can tell you (in my own words) that it&#8217;s a personal mini-process to make you more productive, thus more happy and fulfilled.</p>
<p>It goes like this (from <a href="http://www.pomodorotechnique.com/">www.pomodorotechnique.com</a>):</p>
<ol>
<li>Choose a task to be accomplished</li>
<li>Set the Pomodoro to 25 minutes (the Pomodoro is the timer)</li>
<li>Work on the task until the Pomodoro rings, then put a check on your sheet of paper</li>
<li>Take a short break (5 minutes is OK)</li>
<li>Every 4 Pomodoros take a longer break</li>
</ol>
<p>- where tasks are chosen from your &#8220;todo today&#8221;, which you assemble in the morning by picking tasks from your &#8220;activity inventory&#8221;. There&#8217;s a few more tricks in it, e.g. a form of notation that fits the process well and how to track disturbances.</p>
<p>Having done this for little more than one month, I think I can safely say that it is almost guaranteed to either</p>
<ul>
<li>make you more productive</li>
<li>make you very conscious about <em>why</em> you&#8217;re not that productive</li>
</ul>
<p><img src="http://mookid.dk/oncode/wp-content/2009/12/focus-booster.png" alt="focus-booster" title="focus-booster" width="135" height="88" class="alignright size-full wp-image-880" />Practitioners of the technique usually prefer to use a real egg timer (in the shape of a tomato of course), because of the tactile feedback you get from actually manipulating a physical object &#8211; but as I am sitting in an open office with 6 other developers, and some of them are doing pomodoros as well, we are using the next best thing: a Pomodoro timer app.</p>
<p>Right now I am using the <a href="http://www.focusboosterapp.com/">Focus Booster</a> app, because it&#8217;s pretty and doesn&#8217;t take up that much space on the screen. One of my colleagues, <a href="http://www.blog.troelsrichter.dk/">Troels Richter</a>, is currently working on a more complete Pomodoro app (in Silverlight) that will help in all the aspects of the Pomodoro Technique.</p>
]]></content:encoded>
			<wfw:commentRss>http://mookid.dk/oncode/archives/861/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>NServiceBus for dummies who want to be smarties&#160;6</title>
		<link>http://mookid.dk/oncode/archives/807</link>
		<comments>http://mookid.dk/oncode/archives/807#comments</comments>
		<pubDate>Mon, 30 Nov 2009 09:00:26 +0000</pubDate>
		<dc:creator>mookid</dc:creator>
				<category><![CDATA[nservicebus]]></category>

		<guid isPermaLink="false">http://mookid.dk/oncode/?p=807</guid>
		<description><![CDATA[NServiceBus for dummies who want to be smarties 6&#8230; sixth and last post in the series will show an example using the publish/subscribe functionality provided by NServiceBus.
One could image all kinds of cool integration scenarios where interested parties somehow receive events from our system regarding stuff that may be interesting to them. Let&#8217;s imagine that [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.nservicebus.com/">NServiceBus</a> for dummies who want to be smarties 6&#8230; sixth and last post in the series will show an example using the publish/subscribe functionality provided by NServiceBus.</p>
<p>One could image all kinds of cool integration scenarios where interested parties somehow receive events from our system regarding stuff that may be interesting to them. Let&#8217;s imagine that our user registration from <a href="http://mookid.dk/oncode/archives/755">the fifth post</a> is an extremely interesting event to the sales department and the Über Boss of our enterprise.</p>
<p>To accomodate this, I create a separate assembly meant for holding messages that are not private to our application. This way, I can easily distinguish between messages that I can change whenever I feel like it, and messages that I must put more care and effort into crafting, because they will most likely live forever when a dozen applications in our enterprise are suddenly depending on them.</p>
<p>This means that my saga from the fifth post will handle an email confirmation like this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Handle<span style="color: #000000;">&#40;</span>ConfirmRegistration message<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
      Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Confirming email {0}&quot;</span>, Data.<span style="color: #0000FF;">Email</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
      NewUserService.<span style="color: #0000FF;">CreateNewUserAccount</span><span style="color: #000000;">&#40;</span>Data.<span style="color: #0000FF;">Email</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
      MailSender.<span style="color: #0000FF;">Send</span><span style="color: #000000;">&#40;</span>Data.<span style="color: #0000FF;">Email</span>,
                      <span style="color: #666666;">&quot;Your registration request&quot;</span>,
                      <span style="color: #666666;">&quot;Your email has been confirmed, and your user account has been created&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
      Bus.<span style="color: #0000FF;">Publish</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> SomeoneActuallyRegistered <span style="color: #000000;">&#123;</span>Email <span style="color: #008000;">=</span> Data.<span style="color: #0000FF;">Email</span><span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
      MarkAsComplete<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span></pre></div></div>

<p>As you can see, I <code>Bus.Publish(...)</code> a message saying that someone with a particular email has registered.</p>
<p>To be able to publish stuff, some kind of subscription storage must be configure for the endpoint. Therefore, I change my backend&#8217;s <code>EndpointConfig</code> to be configured with this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">      Configure.<span style="color: #0000FF;">With</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        .<span style="color: #0000FF;">CastleWindsorBuilder</span><span style="color: #000000;">&#40;</span>container<span style="color: #000000;">&#41;</span>
        .<span style="color: #0000FF;">Sagas</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        .<span style="color: #0000FF;">NHibernateSagaPersisterWithSQLiteAndAutomaticSchemaGeneration</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        .<span style="color: #0000FF;">MsmqSubscriptionStorage</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        .<span style="color: #0000FF;">XmlSerializer</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>- which means my backend will be storing subscriptions in a message queue.</p>
<p>If you are somehow unclear on the difference between <em>sending</em> and <em>publishing</em>, I can tell you that the conceptual difference is this: <em>sending</em> is like saying &#8220;do this stuff&#8221;, whereas <em>publishing</em> is like saying &#8220;this stuff happened&#8221; &#8211; see the difference in tense?</p>
<p>Functionally, the difference is that <em>sending</em> will put a message in the queue specified as recipient for that particular message whereafter <em>one</em> recipient will consume that message off its input queue (possibly competing with others), whereas <em>publishing</em> will put a message in the input queue of each one of whoever subscribed to that particular message (possibly many &#8211; possibly zero).</p>
<p>Now, to simulate the sales department and the über boss, I create two new projects containing an app.config that looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;utf-8&quot;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;configSections<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;section</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;MsmqTransportConfig&quot;</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;NServiceBus.Config.MsmqTransportConfig, NServiceBus.Core&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;section</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;UnicastBusConfig&quot;</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;NServiceBus.Config.UnicastBusConfig, NServiceBus.Core&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/configSections<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;MsmqTransportConfig</span> <span style="color: #000066;">InputQueue</span>=<span style="color: #ff0000;">&quot;salesDept&quot;</span></span>
<span style="color: #009900;">                       <span style="color: #000066;">ErrorQueue</span>=<span style="color: #ff0000;">&quot;error&quot;</span></span>
<span style="color: #009900;">                       <span style="color: #000066;">NumberOfWorkerThreads</span>=<span style="color: #ff0000;">&quot;1&quot;</span></span>
<span style="color: #009900;">                       <span style="color: #000066;">MaxRetries</span>=<span style="color: #ff0000;">&quot;5&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;UnicastBusConfig<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;MessageEndpointMappings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;add</span> <span style="color: #000066;">Messages</span>=<span style="color: #ff0000;">&quot;PublicMessages&quot;</span> <span style="color: #000066;">Endpoint</span>=<span style="color: #ff0000;">&quot;backend&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/MessageEndpointMappings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/UnicastBusConfig<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>- and similarly for the über boss.</p>
<p>Note how a subscriber must have a message endpoint mapping telling where messages will be published &#8211; in the example above, my mapping specifies that all messages from my <code>PublicMessages</code> assembly can be subscribe to on the endpoint named &#8220;backend&#8221;. And obviously, a subscriber must have an input queue, through which subscribed messages will be received.</p>
<p>The <code>EndpointConfig</code> can look like this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">namespace</span> SalesDept
<span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> EndpointConfig <span style="color: #008000;">:</span> 
    IConfigureThisEndpoint, 
    AsA_Server, 
    IWantCustomLogging, 
    IWantToRunAtStartup
  <span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> IBus Bus <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Init<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Run<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
      Bus.<span style="color: #0000FF;">Subscribe</span><span style="color: #008000;">&lt;</span>SomeoneActuallyRegistered<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
      Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Sales department running...&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Stop<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
    <span style="color: #000000;">&#125;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>- and similarly for the über boss as well.</p>
<p>Note how the service subscribes to the messages that it wants to receive by calling <code>Bus.Subscribe&lt;...&gt;</code> in the <code>Run()</code> method. What happens, is that NServiceBus somehow communicates to whoever is configured as the publisher of messages of type <code>SomeoneActuallyRegistered</code>, that messages should be sent to <em>this</em> service&#8217;s input queue.</p>
<p>And then, I implement a message hander in each service&#8230; first, the sales department:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">namespace</span> SalesDept
<span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> SendInformationAboutProducts <span style="color: #008000;">:</span> IMessageHandler<span style="color: #008000;">&lt;</span>SomeoneActuallyRegistered<span style="color: #008000;">&gt;</span>
  <span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Handle<span style="color: #000000;">&#40;</span>SomeoneActuallyRegistered message<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
      Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Sending stupid emails to {0}&quot;</span>, message.<span style="color: #0000FF;">Email</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>and then, the über boss:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">namespace</span> ÜberBoss
<span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> NoteEmailInLittleBlackBookOfEvilSchemes <span style="color: #008000;">:</span> IMessageHandler<span style="color: #008000;">&lt;</span>SomeoneActuallyRegistered<span style="color: #008000;">&gt;</span>
  <span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Handle<span style="color: #000000;">&#40;</span>SomeoneActuallyRegistered message<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
      Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Noting email {0}&quot;</span>, message.<span style="color: #0000FF;">Email</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>To make this run, I go to &#8220;Set StartUp projects&#8230;&#8221; of my solution and make all my services start up when I press F5.</p>
<p><img src="http://mookid.dk/oncode/wp-content/2009/11/pic7.png" alt="Picture showing how to configure multiple startup projects" width="782" height="491" class="aligncenter size-full wp-image-847" /></p>
<p>Now, we can check things out by pressing F5, thus running the backend, the sales department, and the über boss at once. On my machine, it looks like this:</p>
<p><img src="http://mookid.dk/oncode/wp-content/2009/11/pic8.png" alt="Running three services at once" width="676" height="434" class="aligncenter size-full wp-image-853" /></p>
<p>Now it doesn&#8217;t take too much imagination to come up with all kinds of cool solutions to integration scenarios.</p>
<h4>Conclusion</h4>
<p>That concludes the sixth and last post in my &#8220;NServiceBus for dummies who want to be smarties&#8221; series. I hope the series can provide some information on how to get started using NServiceBus, and perhaps fill out some of the gaps that comes from documentation in the form of sparsely available blog posts from different sources.</p>
]]></content:encoded>
			<wfw:commentRss>http://mookid.dk/oncode/archives/807/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NServiceBus for dummies who want to be smarties&#160;5</title>
		<link>http://mookid.dk/oncode/archives/755</link>
		<comments>http://mookid.dk/oncode/archives/755#comments</comments>
		<pubDate>Fri, 27 Nov 2009 09:00:13 +0000</pubDate>
		<dc:creator>mookid</dc:creator>
				<category><![CDATA[asp.net mvc]]></category>
		<category><![CDATA[nservicebus]]></category>

		<guid isPermaLink="false">http://mookid.dk/oncode/?p=755</guid>
		<description><![CDATA[NServiceBus for dummies who want to be smarties 5&#8230; fifth post, this time with an example on how sagas can be used to implement a workflow in ASP.NET MVC.
One of the typical workflows in web applications is when someone signs up for an account, but the web site wants to check if the email address [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.nservicebus.com/">NServiceBus</a> for dummies who want to be smarties 5&#8230; fifth post, this time with an example on how sagas can be used to implement a workflow in ASP.NET MVC.</p>
<p>One of the typical workflows in web applications is when someone signs up for an account, but the web site wants to check if the email address is valid. Let&#8217;s look at an example that goes like this:</p>
<ol>
<li>User enters email address as a signup request</li>
<li>Web application sends email with a &#8220;secret&#8221; confirmation link</li>
<li>User visits the secret link, thereby activating the account</li>
</ol>
<p>To keep things simple, I have made a simple page containing two forms: one for the email address, and one that simulates visiting a secret link by letting us enter a &#8220;ticket&#8221;. The view looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;p&gt;
  Enter your email address to begin registration
&lt;/p&gt;
&nbsp;
&lt;form method=&quot;post&quot; action=&quot;!{Url.Action(&quot;BeginRegistration&quot;)}&quot;&gt;
  Email: &lt;input name=&quot;email&quot; type=&quot;text&quot; /&gt;
  &lt;input type=&quot;submit&quot; value=&quot;Begin registration&quot; /&gt;
&lt;/form&gt;
&nbsp;
&lt;p&gt;
  - or enter your ticket to confirm your email
&lt;/p&gt;
&nbsp;
&lt;form method=&quot;post&quot; action=&quot;!{Url.Action(&quot;ConfirmRegistration&quot;)}&quot;&gt;
  Ticket: &lt;input name=&quot;ticket&quot; type=&quot;text&quot; /&gt;
  &lt;input type=&quot;submit&quot; value=&quot;Confirm registration&quot; /&gt;
&lt;/form&gt;</pre></div></div>

<p>And then I have made this simple controller to handle the posts from the registration page:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">  <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> RegistrationController <span style="color: #008000;">:</span> TxBaseController
  <span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">readonly</span> IBus bus<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> RegistrationController<span style="color: #000000;">&#40;</span>IBus bus<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
      <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">bus</span> <span style="color: #008000;">=</span> bus<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> ViewResult Index<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
      <span style="color: #0600FF;">return</span> View<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> RedirectToRouteResult BeginRegistration<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> email<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
      bus.<span style="color: #0000FF;">Send</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> RequestRegistration <span style="color: #000000;">&#123;</span>Email <span style="color: #008000;">=</span> email<span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
      <span style="color: #0600FF;">return</span> RedirectToAction<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Index&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> RedirectToRouteResult ConfirmRegistration<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> ticket<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
      bus.<span style="color: #0000FF;">Send</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> ConfirmRegistration <span style="color: #000000;">&#123;</span>Ticket <span style="color: #008000;">=</span> ticket<span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
      <span style="color: #0600FF;">return</span> RedirectToAction<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Index&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
  <span style="color: #000000;">&#125;</span></pre></div></div>

<p>Now, to model this workflow we need some kind of persistence on our backend, which is where sagas come into the picture. Sagas is the built-in mechanism in NServiceBus that helps in building stateful services. Stateful services are, as the word implies, services that preserve some kind of state between receiving messages.</p>
<p>The NServiceBus saga is a nifty way to declare what that state should contain (by letting a class implement <code>ISagaEntity</code>) and &#8211; given a message that the saga can handle &#8211; how to retrieve that saga (by overriding <code>ConfigureHowToFindSaga</code> and setting up which properties to compare).</p>
<p>Lets start out by specifying that NServiceBus should take care of persisting the saga entity (which will by done through Fluent NHibernate/NHibernate/SQLite under the hood)&#8230; that can easily be achieved by changing our backend&#8217;s endpoint configuration to this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">      Configure.<span style="color: #0000FF;">With</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        .<span style="color: #0000FF;">CastleWindsorBuilder</span><span style="color: #000000;">&#40;</span>container<span style="color: #000000;">&#41;</span>
        .<span style="color: #0000FF;">Sagas</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        .<span style="color: #0000FF;">NHibernateSagaPersisterWithSQLiteAndAutomaticSchemaGeneration</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        .<span style="color: #0000FF;">XmlSerializer</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>This will make NServiceBus persist ongoing sagas in an SQLite db file called &#8220;NServiceBus.Sagas.sqlite&#8221; inside the backend&#8217;s execution directory. If you omit the <code> NHibernateSagaPersisterWithSQLiteAndAutomaticSchemaGeneration()</code> thing, NServiceBus will store ongoing sagas by using its <code>InMemorySagaPersister</code>, which &#8211; surprise! &#8211; stores sagas in memory.</p>
<p>I had some problems with the in-memory persister however, as I could not make it correlate messages with my saga unless I correlated with interned strings only, by implementing getters on my messages like so:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Email
<span style="color: #000000;">&#123;</span> 
    get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> <span style="color: #FF0000;">string</span>.<span style="color: #0000FF;">Intern</span><span style="color: #000000;">&#40;</span>email<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    set <span style="color: #000000;">&#123;</span> email <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>I imagine this has to do with a deserializer somewhere, somehow generating strings that are not interned, although I have not verified this &#8211; I am only guessing! No biggie though, as long as the SQLite saga persister is so easy to use.</p>
<p>In my example the saga is initiated by the <code>RequestRegistration</code> message which contains only an email. When the saga receives that message, the email is stored, and a secret ticket is generated, emailed to the user, and stored in the saga data. The saga is completed when it receives a <code>ConfirmRegistration</code> message with the right ticket.</p>
<p>Let&#8217;s specify what will constitute the saga data:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">  <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> UserRegistrationSagaData <span style="color: #008000;">:</span> ISagaEntity
  <span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">virtual</span> Guid Id <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">virtual</span> <span style="color: #FF0000;">string</span> Originator <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">virtual</span> <span style="color: #FF0000;">string</span> OriginalMessageId <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">virtual</span> <span style="color: #FF0000;">string</span> Email <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">virtual</span> <span style="color: #FF0000;">int</span> Ticket <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
  <span style="color: #000000;">&#125;</span></pre></div></div>

<p>The first three properties come from the <code>ISagaEntity</code> interface &#8211; and then come my two properties for storing the email and the ticket.</p>
<p>Please do remember to mark all the properties of your saga data as <code>virtual</code>! Otherwise, Fluent NHibernate will throw some stupid exception, saying that &#8220;Database was not configured through Database method&#8221; (wtf?) (thanks to <a href="http://blogs.planbsoftware.co.nz/?p=247">this post</a> for sorting that one out!). The exception is fair though, as NHibernate would complain about not being able to create proxies if there were un-interceptable properties on the data class &#8211; the error message is just weird&#8230;</p>
<p>To create a saga, you let a class inherit from <code>Saga&lt;TSagaEntity&gt;</code> where <code>TSagaEntity</code> would be <code>UserRegistrationSagaData</code> in my example&#8230; and then we implement <code>ISagaStartedBy<TMessage></code> and <code>IMessageHandler<TMessage></code> where the two <code>TMessage</code> type parameters should be filled out with <code>RequestRegistration</code> and <code>ConfirmRegistration</code> respectively. Like so:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">  <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> UserRegistrationSaga <span style="color: #008000;">:</span> Saga<span style="color: #008000;">&lt;</span>UserRegistrationSagaData<span style="color: #008000;">&gt;</span>,
    ISagaStartedBy<span style="color: #008000;">&lt;</span>RequestRegistration<span style="color: #008000;">&gt;</span>,
    IMessageHandler<span style="color: #008000;">&lt;</span>ConfirmRegistration<span style="color: #008000;">&gt;</span>
  <span style="color: #000000;">&#123;</span>
     <span style="color: #008080; font-style: italic;">//...</span>
  <span style="color: #000000;">&#125;</span></pre></div></div>

<p>- and then &#8211; given the two kind of messages my saga can handle &#8211; how to correlate the messages with my saga:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #0600FF;">void</span> ConfigureHowToFindSaga<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
      ConfigureMapping<span style="color: #008000;">&lt;</span>RequestRegistration<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>saga <span style="color: #008000;">=&gt;</span> saga.<span style="color: #0000FF;">Email</span>, message <span style="color: #008000;">=&gt;</span> message.<span style="color: #0000FF;">Email</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
      ConfigureMapping<span style="color: #008000;">&lt;</span>ConfirmRegistration<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>saga <span style="color: #008000;">=&gt;</span> saga.<span style="color: #0000FF;">Ticket</span>, message <span style="color: #008000;">=&gt;</span> message.<span style="color: #0000FF;">Ticket</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span></pre></div></div>

<p>Even though my saga is initiated by <code>RequestRegistration</code>, I set up a mapping that ensures that a new saga will not be created if someone requests registration twice with the same email. </p>
<p>Lastly, the actual logic carried out by the saga &#8211; the two message handlers (note that <code>MailSender</code> and <code>NewUserService</code> are application services that are automagically injected becuase they&#8217;re public properties of the saga):</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Handle<span style="color: #000000;">&#40;</span>RequestRegistration message<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
      <span style="color: #008080; font-style: italic;">// generate new ticket if it has not been generated</span>
      <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>Data.<span style="color: #0000FF;">Ticket</span> <span style="color: #008000;">==</span> <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span>
      <span style="color: #000000;">&#123;</span>
        Data.<span style="color: #0000FF;">Ticket</span> <span style="color: #008000;">=</span> NewUserService.<span style="color: #0000FF;">CreateTicket</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
      <span style="color: #000000;">&#125;</span>
&nbsp;
      Data.<span style="color: #0000FF;">Email</span> <span style="color: #008000;">=</span> message.<span style="color: #0000FF;">Email</span><span style="color: #008000;">;</span>
&nbsp;
      MailSender.<span style="color: #0000FF;">Send</span><span style="color: #000000;">&#40;</span>message.<span style="color: #0000FF;">Email</span>,
                      <span style="color: #666666;">&quot;Your registration request&quot;</span>,
                      <span style="color: #666666;">&quot;Please go to /registration/confirm and enter the following ticket: &quot;</span> <span style="color: #008000;">+</span> Data.<span style="color: #0000FF;">Ticket</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
      Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;New registration request for email {0} - ticket is {1}&quot;</span>, Data.<span style="color: #0000FF;">Email</span>, Data.<span style="color: #0000FF;">Ticket</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Handle<span style="color: #000000;">&#40;</span>ConfirmRegistration message<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
      Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Confirming email {0}&quot;</span>, Data.<span style="color: #0000FF;">Email</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
      NewUserService.<span style="color: #0000FF;">CreateNewUserAccount</span><span style="color: #000000;">&#40;</span>Data.<span style="color: #0000FF;">Email</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
      MailSender.<span style="color: #0000FF;">Send</span><span style="color: #000000;">&#40;</span>Data.<span style="color: #0000FF;">Email</span>,
                      <span style="color: #666666;">&quot;Your registration request&quot;</span>,
                      <span style="color: #666666;">&quot;Your email has been confirmed, and your user account has been created&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
      <span style="color: #008080; font-style: italic;">// tell NServiceBus that this saga can be cleaned up afterwards</span>
      MarkAsComplete<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span></pre></div></div>

<p>Note how I mark the saga as complete by calling <code>MarkAsComplete()</code>, thus allowing the saga data to be deleted. This could also be a nifty place to save the time of when the last registration email was sent to a particular address in order to disallow sending another registration email for the next hour or so, to avoid people spamming each other by using our web site.</p>
<p>Now, if I fire up my backend and request registration with the email omg@wtf.com, it looks like this:</p>
<p><img src="http://mookid.dk/oncode/wp-content/2009/11/pic1.png" alt="Submitting email as a registration request" width="448" height="405" class="aligncenter size-full wp-image-789" /><br />
<img src="http://mookid.dk/oncode/wp-content/2009/11/pic2.png" alt="The result on the backend showing that the message was properly received" width="677" height="342" class="aligncenter size-full wp-image-790" /></p>
<p>Then, if I request registration with laterz@hax0rz.com followed by omg@wtf.com, I can verify that a new saga is only created for laterz@hax0rz.com:</p>
<p><img src="http://mookid.dk/oncode/wp-content/2009/11/pic4.png" alt="Submitting the same email twice results in the same ticket being sent out" width="621" height="251" class="aligncenter size-full wp-image-792" /></p>
<p>And then, when I confirm a registration request, it looks like this:</p>
<p><img src="http://mookid.dk/oncode/wp-content/2009/11/pic5.png" alt="Submitting one of the 'secret' tickets" width="448" height="405" class="aligncenter size-full wp-image-793" /><br />
<img src="http://mookid.dk/oncode/wp-content/2009/11/pic6.png" alt="The result on the backend after having submitted on of the tickets" width="621" height="251" class="aligncenter size-full wp-image-798" /></p>
<p>Isn&#8217;t that great? I cannot imagine a framework with an API more elegant and terse than this.</p>
<h4>Conclusion</h4>
<p>That was the fifth post in my &#8220;NServiceBus for dummies who want to be smarties&#8221; series. Sixth and last post will be about our backend publishing messages whenever interesting stuff happens. This will provide a message based interface for interested parties to subscribe to.</p>
]]></content:encoded>
			<wfw:commentRss>http://mookid.dk/oncode/archives/755/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
