<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>mookid on code</title>
	
	<link>http://mookid.dk/oncode</link>
	<description>computers are cool</description>
	<lastBuildDate>Sat, 28 Aug 2010 18:20:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/MookidOnCode" /><feedburner:info uri="mookidoncode" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:browserFriendly></feedburner:browserFriendly><item>
		<title>Scheduling recurring tasks in NServiceBus</title>
		<link>http://mookid.dk/oncode/archives/1507</link>
		<comments>http://mookid.dk/oncode/archives/1507#comments</comments>
		<pubDate>Tue, 10 Aug 2010 21:17:37 +0000</pubDate>
		<dc:creator>mookid</dc:creator>
				<category><![CDATA[nifty]]></category>
		<category><![CDATA[nservicebus]]></category>

		<guid isPermaLink="false">http://mookid.dk/oncode/?p=1507</guid>
		<description><![CDATA[A while ago, on a project I am currently involved with which is based on NServiceBus, we needed to publish certain pieces of information at fixed intervals. I was not totally clear in my head on how this could be implemented in an NServiceBus service, so I asked for help on Twitter, which resulted in <a href='http://mookid.dk/oncode/archives/1507'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>A while ago, on a project I am currently involved with which is based on <a href="http://nservicebus.com/">NServiceBus</a>, we needed to publish certain pieces of information at fixed intervals. I was not totally clear in my head on how this could be implemented in an NServiceBus service, so I asked for help on Twitter, which resulted in a nifty piece of advice from <a href="http://twitter.com/andreasohlund/">Andreas Öhlund</a>: Set up a timer to do a <code>bus.SendLocal</code> at the specified interval.</p>
<p>That&#8217;s exactly what we did, and I think we ended up with a pretty nifty piece of code that I want to show off <img src='http://mookid.dk/oncode/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>PS: <code>bus.SendLocal(message)</code> effectively does a <code>bus.Send(((UnicastBus)bus).Address, message)</code> &#8211; i.e. it puts a message, MSMQ and all, in the service&#8217;s own input queue.</p>
<p>First, we have an API that looks like this (looking a little funny, I know &#8211; wait and see&#8230;):</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> ISchedule
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">void</span> Every<span style="color: #000000;">&#40;</span>TimeSpan interval, Func<span style="color: #008000;">&lt;</span>IMessage<span style="color: #008000;">&gt;</span> messageFactoryMethod<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>- which is implemented like this (registered as a singleton in the container):</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> ServerBasedTimerSchedule <span style="color: #008000;">:</span> ISchedule, IDisposable
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">readonly</span> IBus bus<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">readonly</span> List<span style="color: #008000;">&lt;</span><span style="color: #000000;">System.<span style="color: #0000FF;">Timers</span></span>.<span style="color: #0000FF;">Timer</span><span style="color: #008000;">&gt;</span> timers <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span><span style="color: #000000;">System.<span style="color: #0000FF;">Timers</span></span>.<span style="color: #0000FF;">Timer</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> ServerBasedTimerSchedule<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> <span style="color: #0600FF;">void</span> Every<span style="color: #000000;">&#40;</span>TimeSpan interval, Func<span style="color: #008000;">&lt;</span>IMessage<span style="color: #008000;">&gt;</span> messageFactoryMethod<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        var timer <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #000000;">System.<span style="color: #0000FF;">Timers</span></span>.<span style="color: #0000FF;">Timer</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        timer.<span style="color: #0000FF;">Elapsed</span> <span style="color: #008000;">+=</span> <span style="color: #000000;">&#40;</span>_, __<span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span> bus.<span style="color: #0000FF;">SendLocal</span><span style="color: #000000;">&#40;</span>messageFactoryMethod<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        timer.<span style="color: #0000FF;">Interval</span> <span style="color: #008000;">=</span> interval.<span style="color: #0000FF;">TotalMilliseconds</span><span style="color: #008000;">;</span>
        timer.<span style="color: #0000FF;">Start</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        timers.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>timer<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> Dispose<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        timers.<span style="color: #0600FF;">ForEach</span><span style="color: #000000;">&#40;</span>timer <span style="color: #008000;">=&gt;</span> timer.<span style="color: #0000FF;">Dispose</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</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>The <code>System.Timers.Timer</code> is a timer which uses the thread pool to schedule callbacks at the specified interval. It&#8217;s pretty easy to use, and it fits nicely with this scenario.</p>
<p>Now, in combination with this nifty class of extension goodness:</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;">static</span> <span style="color: #FF0000;">class</span> TimeSpanExtensions
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> TimeSpan Seconds<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">this</span> <span style="color: #FF0000;">int</span> seconds<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">return</span> TimeSpan.<span style="color: #0000FF;">FromSeconds</span><span style="color: #000000;">&#40;</span>seconds<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;">static</span> TimeSpan Minutes<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">this</span> <span style="color: #FF0000;">int</span> minutes<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">return</span> TimeSpan.<span style="color: #0000FF;">FromMinutes</span><span style="color: #000000;">&#40;</span>minutes<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// ... etc + for doubles as well</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>- we can schedule our tasks 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> ScheduleRealTimeDataPublishing <span style="color: #008000;">:</span> IWantToRunAtStartup
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> ScheduleRealTimeDataPublishing<span style="color: #000000;">&#40;</span>ISchedule schedule<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">schedule</span> <span style="color: #008000;">=</span> schedule<span style="color: #008000;">;</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>
        schedule.<span style="color: #0000FF;">Every</span><span style="color: #000000;">&#40;</span>5.<span style="color: #0000FF;">Seconds</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span> <span style="color: #008000;">new</span> PublishRealTimeDataMessage<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</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></pre></div></div>

<p>Now, why is this good? It&#8217;s good because the actual task will then be carried out by whoever implements <code>IHandleMessages&lt;PublishRealTimeDataMessage&gt;</code> in the service, processing the tasks with all the benefits of the usual NServiceBus message processing pipeline.</p>
<p>Nifty, huh?</p>
<p>Looking over the simplicity and elegance of this solution, I&#8217;m kind of embarassed to tell that my first take on this was to implement the timer almost exactly like above, except instead of <code>bus.SendLocal</code> in the <code>Elapsed</code>-callback, we had a huge event handler that simulated most of our message processing pipeline &#8211; including <code>NHibernateMessageModule</code>, transactions, and whatnot&#8230;.</p>
<p>Please note that <code>ScheduleRealTimeDataPublishing</code> is not re-entrant &#8211; in this form its <code>Every</code> method should only be used from within the <code>Run</code> and <code>Stop</code> methods of implementors of <code>IWantToRunAtStartup</code>, as these are run sequentially.</p>
]]></content:encoded>
			<wfw:commentRss>http://mookid.dk/oncode/archives/1507/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Code golf</title>
		<link>http://mookid.dk/oncode/archives/1487</link>
		<comments>http://mookid.dk/oncode/archives/1487#comments</comments>
		<pubDate>Fri, 30 Jul 2010 20:09:44 +0000</pubDate>
		<dc:creator>mookid</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[nifty]]></category>

		<guid isPermaLink="false">http://mookid.dk/oncode/?p=1487</guid>
		<description><![CDATA[The result of Kodehoved&#8217;s code golf competition has been found, and I got a shared 5th place. The task was to add two large integers together by representing the integers with arrays of their digits, thus allowing them to become extremely large. My contribution looks like this (weighing in at 138 characters): public static int&#91;&#93; <a href='http://mookid.dk/oncode/archives/1487'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>The result of Kodehoved&#8217;s <a href="http://kodehoved.dk/?p=530">code golf</a> competition has been found, and I got a shared 5th place.</p>
<p>The task was to add two large integers together by representing the integers with arrays of their digits, thus allowing them to become extremely large.</p>
<p>My contribution looks like this (weighing in at 138 characters):</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;">static</span> <span style="color: #FF0000;">int</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> Mookid8000_Add<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> a,<span style="color: #FF0000;">int</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> b<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
   var r<span style="color: #008000;">=</span><span style="color: #666666;">&quot;&quot;</span><span style="color: #008000;">;</span>
   <span style="color: #0600FF;">for</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> n<span style="color: #008000;">=</span>a.<span style="color: #0000FF;">Length</span>,m<span style="color: #008000;">=</span>b.<span style="color: #0000FF;">Length</span>,s,c<span style="color: #008000;">=</span><span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>n<span style="color: #008000;">+</span>m<span style="color: #008000;">+</span>c<span style="color: #008000;">&gt;</span><span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>c<span style="color: #008000;">=</span>s<span style="color: #008000;">/</span><span style="color: #FF0000;">10</span><span style="color: #000000;">&#41;</span>
      r<span style="color: #008000;">=</span><span style="color: #000000;">&#40;</span>s<span style="color: #008000;">=</span><span style="color: #000000;">&#40;</span>n<span style="color: #008000;">&gt;</span><span style="color: #FF0000;">0</span><span style="color: #008000;">?</span>a<span style="color: #000000;">&#91;</span><span style="color: #008000;">--</span>n<span style="color: #000000;">&#93;</span><span style="color: #008000;">:</span><span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">+</span><span style="color: #000000;">&#40;</span>m<span style="color: #008000;">&gt;</span><span style="color: #FF0000;">0</span><span style="color: #008000;">?</span>b<span style="color: #000000;">&#91;</span><span style="color: #008000;">--</span>m<span style="color: #000000;">&#93;</span><span style="color: #008000;">:</span><span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">+</span>c<span style="color: #000000;">&#41;</span><span style="color: #008000;">%</span>10<span style="color: #008000;">+</span>r<span style="color: #008000;">;</span>
   <span style="color: #0600FF;">return</span> r.<span style="color: #0000FF;">Select</span><span style="color: #000000;">&#40;</span>t<span style="color: #008000;">=&gt;</span>t<span style="color: #008000;">-</span><span style="color: #FF0000;">48</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: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p><a href="http://twitter.com/asgerhallas">Asger</a>&#8216;s and <a href="http://twitter.com/larsudengaard">Lars</a>&#8216; contribution looks like this (135 characters):</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;">static</span> <span style="color: #FF0000;">int</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> AsgerHallasOgLarsUdengaard_Add<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> a,<span style="color: #FF0000;">int</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> b<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
   var r<span style="color: #008000;">=</span><span style="color: #666666;">&quot;&quot;</span><span style="color: #008000;">;</span>
   <span style="color: #0600FF;">for</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> c<span style="color: #008000;">=</span><span style="color: #FF0000;">0</span>,x<span style="color: #008000;">=</span>a.<span style="color: #0000FF;">Length</span>,y<span style="color: #008000;">=</span>b.<span style="color: #0000FF;">Length</span><span style="color: #008000;">;</span>x<span style="color: #008000;">+</span>y<span style="color: #008000;">&gt;</span><span style="color: #FF0000;">0</span><span style="color: #008000;">|</span>c<span style="color: #008000;">&gt;</span><span style="color: #FF0000;">9</span><span style="color: #008000;">;</span><span style="color: #000000;">&#41;</span>
      r<span style="color: #008000;">=</span><span style="color: #000000;">&#40;</span>c<span style="color: #008000;">=</span><span style="color: #000000;">&#40;</span>x<span style="color: #008000;">&gt;</span><span style="color: #FF0000;">0</span><span style="color: #008000;">?</span>a<span style="color: #000000;">&#91;</span><span style="color: #008000;">--</span>x<span style="color: #000000;">&#93;</span><span style="color: #008000;">:</span><span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">+</span><span style="color: #000000;">&#40;</span>y<span style="color: #008000;">&gt;</span><span style="color: #FF0000;">0</span><span style="color: #008000;">?</span>b<span style="color: #000000;">&#91;</span><span style="color: #008000;">--</span>y<span style="color: #000000;">&#93;</span><span style="color: #008000;">:</span><span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">+</span>c<span style="color: #008000;">/</span><span style="color: #FF0000;">10</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">%</span>10<span style="color: #008000;">+</span>r<span style="color: #008000;">;</span>
   <span style="color: #0600FF;">return</span> r.<span style="color: #0000FF;">Select</span><span style="color: #000000;">&#40;</span>s<span style="color: #008000;">=&gt;</span>s<span style="color: #008000;">-</span><span style="color: #FF0000;">48</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: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>And the winners&#8217; (<a href="http://mpbrun.dk/">Mads and Peter Sandberg Brun</a>) contribution looks like this (weighing in at an incredibly compact, but almost unreadable, 132 characters <img src='http://mookid.dk/oncode/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ):</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;">static</span> <span style="color: #FF0000;">int</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> MadsOgPeterSandbergBrun_Add<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> a,<span style="color: #FF0000;">int</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> b<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>  
   var c<span style="color: #008000;">=</span><span style="color: #666666;">&quot;&quot;</span><span style="color: #008000;">;</span>  
   <span style="color: #0600FF;">for</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> o<span style="color: #008000;">=</span>a.<span style="color: #0000FF;">Length</span>,p<span style="color: #008000;">=</span>b.<span style="color: #0000FF;">Length</span>,s<span style="color: #008000;">=</span><span style="color: #FF0000;">0</span><span style="color: #008000;">;-</span>o<span style="color: #008000;">-</span>p<span style="color: #008000;">&lt;</span><span style="color: #000000;">&#40;</span>s<span style="color: #008000;">=</span>s<span style="color: #008000;">/</span><span style="color: #FF0000;">10</span><span style="color: #008000;">+</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">0</span><span style="color: #008000;">&lt;</span>o<span style="color: #008000;">?</span>a<span style="color: #000000;">&#91;</span><span style="color: #008000;">--</span>o<span style="color: #000000;">&#93;</span><span style="color: #008000;">:</span><span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">+</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">0</span><span style="color: #008000;">&lt;</span>p<span style="color: #008000;">?</span>b<span style="color: #000000;">&#91;</span><span style="color: #008000;">--</span>p<span style="color: #000000;">&#93;</span><span style="color: #008000;">:</span><span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span><span style="color: #000000;">&#41;</span>  
      c<span style="color: #008000;">=</span>s<span style="color: #008000;">%</span>10<span style="color: #008000;">+</span>c<span style="color: #008000;">;</span>  
   <span style="color: #0600FF;">return</span> c.<span style="color: #0000FF;">Select</span><span style="color: #000000;">&#40;</span>i<span style="color: #008000;">=&gt;</span>i<span style="color: #008000;">-</span><span style="color: #FF0000;">48</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: #008000;">;</span>  
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>I usually don&#8217;t compete in competitions like this, because I&#8217;ve always thought of myself as pretty lame when it comes to solving coding puzzles, but this time it was great fun &#8211; especially since I was pretty motivated by my desire to beat <a href="http://twitter.com/asgerhallas">Asger</a> (my little sister&#8217;s boyfriend), who pushed me several iterations further than I would have gone on my own. He ended up beating me though, but I am still pretty satisfied with my fairly compact and almost readable solution.</p>
]]></content:encoded>
			<wfw:commentRss>http://mookid.dk/oncode/archives/1487/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fun with NoRM 4</title>
		<link>http://mookid.dk/oncode/archives/1452</link>
		<comments>http://mookid.dk/oncode/archives/1452#comments</comments>
		<pubDate>Mon, 26 Jul 2010 08:00:34 +0000</pubDate>
		<dc:creator>mookid</dc:creator>
				<category><![CDATA[NoRM]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[nosql]]></category>

		<guid isPermaLink="false">http://mookid.dk/oncode/?p=1452</guid>
		<description><![CDATA[This time, a short post on how to model inheritance, which (at least in a class-oriented programming language) is one of the foundations of object-oriented programming. Let&#8217;s take an example with a person, who has a home address that can be either domestic or foreign. Consider this: public class Person &#123; public string FirstName &#123; <a href='http://mookid.dk/oncode/archives/1452'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>This time, a short post on how to model inheritance, which (at least in a class-oriented programming language) is one of the foundations of object-oriented programming.</p>
<p>Let&#8217;s take an example with a person, who has a home address that can be either domestic or foreign. Consider 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;">class</span> Person
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> FirstName <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: #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> Address HomeAddress <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> abstract <span style="color: #FF0000;">class</span> Address
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> abstract <span style="color: #FF0000;">string</span> FormatAddress<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> separator<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> DomesticAddress <span style="color: #008000;">:</span> Address
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Street <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: #FF0000;">string</span> Number <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: #FF0000;">string</span> PostalCode <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: #FF0000;">string</span> City <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: #008080; font-style: italic;">// and 17 other fields here, according to whatever is standard in your country</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #FF0000;">string</span> FormatAddress<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> separator<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">return</span> <span style="color: #FF0000;">string</span>.<span style="color: #0000FF;">Join</span><span style="color: #000000;">&#40;</span>separator, <span style="color: #008000;">new</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#123;</span> Street <span style="color: #008000;">+</span> <span style="color: #666666;">&quot; &quot;</span> <span style="color: #008000;">+</span> Number, PostalCode <span style="color: #008000;">+</span> <span style="color: #666666;">&quot; &quot;</span> <span style="color: #008000;">+</span> City <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>
&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> ForeignAddress <span style="color: #008000;">:</span> Adress
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> AddressLines <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> FormatAddress<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> separator<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">return</span> <span style="color: #FF0000;">string</span>.<span style="color: #0000FF;">Join</span><span style="color: #000000;">&#40;</span>separator, AddressLines<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, when I create a <code>Person</code> with a <code>DomesticAddress</code> and save it to my local Mongo, it looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var people <span style="color: #008000;">=</span> mongo.<span style="color: #0000FF;">GetCollection</span><span style="color: #008000;">&lt;</span>Person<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
people.<span style="color: #0000FF;">Insert</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> Person
<span style="color: #000000;">&#123;</span> 
    FirstName <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Mogens Heller&quot;</span>, 
    LastName <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Grabe&quot;</span>,
    HomeAddress <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DomesticAddress 
    <span style="color: #000000;">&#123;</span> 
        Street <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Torsmark&quot;</span>, 
        Number <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;4&quot;</span>, 
        <span style="color: #008080; font-style: italic;">// etc</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>which is all fine and dandy &#8211; and in the db:</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;">Person</span>.<span style="color: #660066;">findOne</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #3366CC;">&quot;FirstName&quot;</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Mogens Heller&quot;</span><span style="color: #339933;">,</span>
    <span style="color: #3366CC;">&quot;LastName&quot;</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Grabe&quot;</span><span style="color: #339933;">,</span>
    <span style="color: #3366CC;">&quot;HomeAddress&quot;</span><span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #3366CC;">&quot;Street&quot;</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Torsmark&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #3366CC;">&quot;Number&quot;</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;4&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #006600; font-style: italic;">// etc...</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>which looks pretty good as well. BUT when I try to load the person again by doing this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var people <span style="color: #008000;">=</span> mongo.<span style="color: #0000FF;">GetCollection</span><span style="color: #008000;">&lt;</span>Person<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
var me <span style="color: #008000;">=</span> people.<span style="color: #0000FF;">FindOne</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>I get BOOM!!: <code>Norm.MongoException: Could not find the type to instantiate in the document, and Address is an interface or abstract type. Add a MongoDiscriminatedAttribute to the type or base type, or try to work with a concrete type next time.</code></p>
<p>Why of course! JSON (hence BSON) only specifies objects &#8211; even though we consider them to be logical instances of some class, they&#8217;re actually not! &#8211; they&#8217;re just objects!</p>
<p>So, we need to help NoRM a little bit. Actually the exception message says it all: Add a <code>MongoDiscriminated</code> attribute to the abstract base class, like so:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>MongoDiscriminated<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> abstract <span style="color: #FF0000;">class</span> Address
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> abstract <span style="color: #FF0000;">string</span> FormatAddress<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> separator<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>That was easy. Now, if I do a <code>db.People.drop()</code>, followed by my <code>people.Insert(...)</code>-code from before, I get this in the db:</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;">Person</span>.<span style="color: #660066;">findOne</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #3366CC;">&quot;FirstName&quot;</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Mogens Heller&quot;</span><span style="color: #339933;">,</span>
    <span style="color: #3366CC;">&quot;LastName&quot;</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Grabe&quot;</span><span style="color: #339933;">,</span>
    <span style="color: #3366CC;">&quot;HomeAddress&quot;</span><span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #3366CC;">&quot;__type&quot;</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;MongoTest.DomesticAddress, MongoTest&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #3366CC;">&quot;Street&quot;</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Torsmark&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #3366CC;">&quot;Number&quot;</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;4&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #006600; font-style: italic;">// etc...</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>See the <code>__type</code> field that NoRM added to the object? As you can see, it contains the assembly-qualified name of the concrete type that resulted in that particular object, allowing NoRM to deserialize properly when loading from the db.</p>
<p>Now, this actually makes working with inheritance hierarchies and specialization pretty easy &#8211; just add <code>[MongoDiscriminated]</code> to a base class, resulting in concrete type information being saved along with objects of any derived type.</p>
<p>Only thing that would be better is if NoRM would issue a warning or an exception when saving something that could not be properly deserialized &#8211; this way, one would not easily get away with saving stuff that could not (easily) be retrieved again.</p>
]]></content:encoded>
			<wfw:commentRss>http://mookid.dk/oncode/archives/1452/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fun with NoRM 3</title>
		<link>http://mookid.dk/oncode/archives/1418</link>
		<comments>http://mookid.dk/oncode/archives/1418#comments</comments>
		<pubDate>Thu, 22 Jul 2010 08:00:07 +0000</pubDate>
		<dc:creator>mookid</dc:creator>
				<category><![CDATA[NoRM]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[nifty]]></category>
		<category><![CDATA[nosql]]></category>

		<guid isPermaLink="false">http://mookid.dk/oncode/?p=1418</guid>
		<description><![CDATA[Third post in &#8220;Fun With NoRM&#8221; will be about how &#8220;the dynamism&#8221; of JavaScript and JSON is bridged into the rigid and statically typed world of C#. The thing is, in principle there&#8217;s no way to be certain that a JSON object returned from MongoDB will actually fit into our static object model. Consider a <a href='http://mookid.dk/oncode/archives/1418'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Third post in &#8220;Fun With NoRM&#8221; will be about how &#8220;the dynamism&#8221; of JavaScript and JSON is bridged into the rigid and statically typed world of C#. The thing is, in principle there&#8217;s no way to be certain that a JSON object returned from MongoDB will actually fit into our static object model. </p>
<p>Consider a situation where, for some reason, some of our orders have a field, <code>PlacedBy</code>, containing the name of the person who placed the order. Let&#8217;s see how things will go when adding the field and then querying all orders:</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;">use</span> dbname
<span style="color: #339933;">&gt;</span> <span style="color: #003366; font-weight: bold;">var</span> order <span style="color: #339933;">=</span> db.<span style="color: #660066;">Order</span>.<span style="color: #660066;">findOne</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&gt;</span> order.<span style="color: #660066;">PlacedBy</span> <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;El Duderino&quot;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&gt;</span> db.<span style="color: #660066;">Order</span>.<span style="color: #660066;">save</span><span style="color: #009900;">&#40;</span>order<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var orders <span style="color: #008000;">=</span> mongo.<span style="color: #0000FF;">GetCollection</span><span style="color: #008000;">&lt;</span>Order<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">foreach</span><span style="color: #000000;">&#40;</span>var order <span style="color: #0600FF;">in</span> orders.<span style="color: #0000FF;">Find</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</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;Order #{0}&quot;</span>, order.<span style="color: #0000FF;">Number</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>- and BOOM ! &#8211; Cannot deserialize!: <code>Norm.MongoException: Deserialization failed: type MongoTest.Order does not have a property named PlacedBy</code></p>
<p>This is actually pretty good, because this way we will never accidentally load a document with un-deserializable properties and save it back, thus truncating the document. But how can we handle this?</p>
<p>Well, NoRM makes it pretty easy: Make your model class inherit <code>Expando</code>, thus effectively becoming a dictionary. E.g. 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> Order <span style="color: #008000;">:</span> Expando
<span style="color: #000000;">&#123;</span>
   <span style="color: #008080; font-style: italic;">// ...</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Now we can do this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var orders <span style="color: #008000;">=</span> mongo.<span style="color: #0000FF;">GetCollection</span><span style="color: #008000;">&lt;</span>Order<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">foreach</span><span style="color: #000000;">&#40;</span>var order <span style="color: #0600FF;">in</span> orders.<span style="color: #0000FF;">Find</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</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;Order #{0}&quot;</span>, order.<span style="color: #0000FF;">Number</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>order.<span style="color: #0000FF;">AllProperties</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Any</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        var props <span style="color: #008000;">=</span> order.<span style="color: #0000FF;">AllProperties</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Select</span><span style="color: #000000;">&#40;</span>p <span style="color: #008000;">=&gt;</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}: {1}&quot;</span>, p.<span style="color: #0000FF;">PropertyName</span>, p.<span style="color: #0000FF;">Value</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;<span style="color: #008080; font-weight: bold;">\t</span>{0}&quot;</span>, <span style="color: #FF0000;">string</span>.<span style="color: #0000FF;">Join</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;, &quot;</span>, props.<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: #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 yields:</p>

<div class="wp_syntax"><div class="code"><pre class="dos" style="font-family:monospace;">Order #<span style="color: #cc66cc;">1</span>
    PlacedBy: El Duderino
Order #<span style="color: #cc66cc;">2</span>
Order #<span style="color: #cc66cc;">3</span></pre></div></div>

<p>when run with a small DB containing three orders. Nifty, huh?</p>
<p>If you&#8217;re sad that you&#8217;ve given up your single opportunity to inherit something by deriving from <code>Expando</code>, just go ahead and implement <code>IExpando</code> instead. Then you need to suply a few members, but you can just redirect to an internal <code>Expando</code> in your class.</p>
<p>Next up, a post on how to model inheritance hierarchies&#8230; one of my favorites! <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/1418/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fun with NoRM 2</title>
		<link>http://mookid.dk/oncode/archives/1407</link>
		<comments>http://mookid.dk/oncode/archives/1407#comments</comments>
		<pubDate>Mon, 19 Jul 2010 08:00:41 +0000</pubDate>
		<dc:creator>mookid</dc:creator>
				<category><![CDATA[NoRM]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[nosql]]></category>

		<guid isPermaLink="false">http://mookid.dk/oncode/?p=1407</guid>
		<description><![CDATA[This second post in &#8220;Fun With NoRM&#8221; will be about querying&#8230; How to get everything Querying collections can be done easily with the anonymous types of C# 3 &#8211; e.g. the Order collection from my previous post can be queried for all orders like so: var orders = mongo.GetCollection&#60;Order&#62;&#40;&#41;; &#160; var allOrders = orders.Find&#40;&#41;; How <a href='http://mookid.dk/oncode/archives/1407'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>This second post in &#8220;Fun With NoRM&#8221; will be about querying&#8230;</p>
<h4>How to get everything</h4>
<p>Querying collections can be done easily with the anonymous types of C# 3 &#8211; e.g. the <code>Order</code> collection from my <a href="http://mookid.dk/oncode/archives/1391">previous post</a> can be queried for all orders like so:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var orders <span style="color: #008000;">=</span> mongo.<span style="color: #0000FF;">GetCollection</span><span style="color: #008000;">&lt;</span>Order<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
var allOrders <span style="color: #008000;">=</span> orders.<span style="color: #0000FF;">Find</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<h4>How to use criteria</h4>
<p>If we&#8217;re looking for some particular order, we can query by field values like so:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var orderNumber2 <span style="color: #008000;">=</span> orders.<span style="color: #0000FF;">Find</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> <span style="color: #000000;">&#123;</span> Number <span style="color: #008000;">=</span> <span style="color: #FF0000;">2</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>or by using the query operators residing in the static class <code>Q</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var ordersWithNumberGreaterThan2 <span style="color: #008000;">=</span> orders.<span style="color: #0000FF;">Find</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> <span style="color: #000000;">&#123;</span> Number <span style="color: #008000;">=</span> Q.<span style="color: #0000FF;">GreaterThan</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">2</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<h4>More advanced criteria</h4>
<p>The query operators can even be combined by combining criteria like so:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var ordersWithNumberBetween5And10 <span style="color: #008000;">=</span> orders.<span style="color: #0000FF;">Find</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> <span style="color: #000000;">&#123;</span> Number <span style="color: #008000;">=</span> Q.<span style="color: #0000FF;">GreaterThan</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">5</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">And</span>.<span style="color: #0000FF;">LessThan</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">10</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Now, what about the nifty <a href="http://www.mongodb.org/display/DOCS/Dot+Notation+(Reaching+into+Objects)">dot notation</a>? This an example where C#&#8217;s capabilities don&#8217;t cut it anymore, as everything on the left side in an anonymous type need to be valid identifiers &#8211; so no dots in property names!</p>
<p>This is solved in NoRM by introducing <code>Expando</code>! (not to be confused with <code>ExpandoObject</code> of .NET 4, even though they have similarities&#8230;)</p>
<p><code>Expando</code> is just a dictionary, so to query by the field of an embedded object, do it like so:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var q <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Expando<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
q<span style="color: #000000;">&#91;</span><span style="color: #666666;">&quot;Items.Name&quot;</span><span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;beer&quot;</span><span style="color: #008000;">;</span>
var ordersWithBeer <span style="color: #008000;">=</span> orders.<span style="color: #0000FF;">Find</span><span style="color: #000000;">&#40;</span>q<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>As you can see, querying with NoRM is pretty easy &#8211; and I think the NoRM guys have found a pretty decent workaround in the case of dot notation, where C#&#8217;s syntax could not be bent further.</p>
<p>Stay tuned for more posts&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://mookid.dk/oncode/archives/1407/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fun with NoRM 1</title>
		<link>http://mookid.dk/oncode/archives/1391</link>
		<comments>http://mookid.dk/oncode/archives/1391#comments</comments>
		<pubDate>Fri, 16 Jul 2010 08:00:23 +0000</pubDate>
		<dc:creator>mookid</dc:creator>
				<category><![CDATA[NoRM]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[nifty]]></category>
		<category><![CDATA[nosql]]></category>

		<guid isPermaLink="false">http://mookid.dk/oncode/?p=1391</guid>
		<description><![CDATA[My previous posts on MongoDB have been pretty un-.NETty, in that I have focused almost entirely on how to work the DB through its JavaScript API. To remedy that, I shall write a few short posts on how to get rolling with MongoDB using NoRM, the coolest C# driver for MongoDB at the moment. First <a href='http://mookid.dk/oncode/archives/1391'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>My <a href="http://mookid.dk/oncode/?s=checking+out+mongodb&#038;searchsubmit=">previous posts on MongoDB</a> have been pretty un-.NETty, in that I have focused almost entirely on how to work the DB through its JavaScript API. To remedy that, I shall write a few short posts on how to get rolling with MongoDB using <a href="http://wiki.github.com/atheken/NoRM/">NoRM</a>, the coolest C# driver for MongoDB at the moment.</p>
<p>First post will be on how to connect and shove data into MongoDB.</p>
<h4>Short introduction to NoRM</h4>
<p>NoRM is &#8220;No Object-Relational Mapping&#8221;. It&#8217;s a .NET-driver, that allows you to map objects and their fields and aggregated objects into documents. I like NoRM because it&#8217;s successfully preserved that low-friction MongoDB-feeling, bridging C#&#8217;s capabilities nicely to those of JavaScript in the best possible way, providing some extra C#-goodies along the way. Please read on, you&#8217;ll see&#8230;</p>
<h4>Connect to MongoDB</h4>
<p>Easy &#8211; can be done like so:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span><span style="color: #000000;">&#40;</span>var mongo <span style="color: #008000;">=</span> Mongo.<span style="color: #0000FF;">Create</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;mongodb://hostname/dbname&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
   <span style="color: #008080; font-style: italic;">// go crazy in here!!1</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<h4>Inserting a few documents</h4>
<p>Inserting documents with NoRM is easy &#8211; just create a class with fields and aggregated objects, and make sure the class either has a property named something like &#8220;Id&#8221; or has a property decorated with <code>[MongoIdentifier]</code>, e.g. 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> Order
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> Order<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Id <span style="color: #008000;">=</span> ObjectId.<span style="color: #0000FF;">NewObjectID</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Items <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span>Item<span style="color: #008000;">&gt;</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;
    <span style="color: #0600FF;">public</span> ObjectId 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: #FF0000;">int</span> Number <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> List<span style="color: #008000;">&lt;</span>Item<span style="color: #008000;">&gt;</span> Items <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> Item
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Name <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: #FF0000;">int</span> Amount <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 go ahead and pull a strongly typed collection and insert documents into it:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var orders <span style="color: #008000;">=</span> mongo.<span style="color: #0000FF;">GetCollection</span><span style="color: #008000;">&lt;</span>Order<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
orders.<span style="color: #0000FF;">Insert</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> Order <span style="color: #000000;">&#123;</span>
    Number <span style="color: #008000;">=</span> <span style="color: #FF0000;">1</span>,
    Items <span style="color: #008000;">=</span> <span style="color: #000000;">&#123;</span>
        <span style="color: #008000;">new</span> Item <span style="color: #000000;">&#123;</span> Name <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;beer&quot;</span> <span style="color: #000000;">&#125;</span>,
        <span style="color: #008000;">new</span> Item <span style="color: #000000;">&#123;</span> Name <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;nuts&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></pre></div></div>

<p>Now, to make this work I need to create five 200-line XML-files with mapping info etc. <code>&lt;/kidding&gt;</code> no, seriously &#8211; that&#8217;s all it takes to persist an entire aggregate root!!</p>
<p>Pretty cool, eh? That&#8217;s what I meant when I said low friction. Stay tuned for more posts, e.g. on how to query a collection&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://mookid.dk/oncode/archives/1391/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>So you think you’re domain-driven?</title>
		<link>http://mookid.dk/oncode/archives/1359</link>
		<comments>http://mookid.dk/oncode/archives/1359#comments</comments>
		<pubDate>Thu, 24 Jun 2010 14:00:48 +0000</pubDate>
		<dc:creator>mookid</dc:creator>
				<category><![CDATA[ddd]]></category>

		<guid isPermaLink="false">http://mookid.dk/oncode/?p=1359</guid>
		<description><![CDATA[In a project I am currently involved with, a core part of the system involves a couple of fairly complicated (at least to me ) computations involving time, power, energy, fuel, volumes etc. At first, we just implemented the computations &#8220;as specified&#8221;, i.e. we went ahead and did stuff like this: public double GetRemainingCapacity&#40;&#41; &#123; <a href='http://mookid.dk/oncode/archives/1359'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>In a project I am currently involved with, a core part of the system involves a couple of fairly complicated (at least to me <img src='http://mookid.dk/oncode/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ) computations involving time, power, energy, fuel, volumes etc. </p>
<p>At first, we just implemented the computations &#8220;as specified&#8221;, i.e. we went ahead and did stuff 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;">double</span> GetRemainingCapacity<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">double</span> remainingRuntimeHours <span style="color: #008000;">=</span> remainingRuntimeSeconds <span style="color: #008000;">/</span> <span style="color: #FF0000;">3600</span><span style="color: #008000;">;</span>
    <span style="color: #FF0000;">double</span> remainingCapacityMWh <span style="color: #008000;">=</span> currentProductionKW <span style="color: #008000;">*</span> remainingRuntimeHours <span style="color: #008000;">/</span> <span style="color: #FF0000;">1000</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF;">return</span> remainingCapacityMWh<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>to calculate how many MHhs a given device can deliver. This is just an example, we have a lot of this stuff going on, and this will be a major extensibility point in the system in the future.</p>
<p>I don&#8217;t know about you, but I got a tiny headache every time I looked at code like this, part from trying to understand what was going on, part because I knew errors could hide in there forever.</p>
<p>To remedy my headache (and the other team members&#8217; headaches), we started migrating all that funky <code>double</code> stuff to some types, that do a better job at representing &#8211; i.e. <code>Power</code> for power, <code>Energy</code> for energy, and so on! </p>
<p>All of them, of course, as proper immutable value types (even though we use classes for that).</p>
<p>And then we utilized C#&#8217;s ability to supply <em>operator overloading</em> on all our domain types, allowing stuff like this to happen:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> Energy GetRemainingCapacity<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">return</span> currentProduction <span style="color: #008000;">*</span> remainingRuntime<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>where <code>currentProduction</code> is an instance of <code>Power</code> and <code>remainingRuntime</code> is a <code>TimeSpan</code>. And whoever gets the <code>Energy</code> that comes out of this, will never have to doubt whether its Whs, KWhs, or MWhs &#8211; it&#8217;s just pure energy!</p>
<p>Now, this may seem like a small change, but it has already proven to have huge ramifications for the way we implement our computations:</p>
<ol>
<li>There is no such thing as multiplying two powers by accident, or subtracting two values that cannot be subtracted and still make sense, etc.</li>
<li>We have no errors due to wrong factors, e.g. like KWs mistakenly being treated as MWs</li>
<li><em>We have gained a cleaner, more intuitive core API, which is just friggin&#8217; sweet!</em></li>
</ol>
<p>In retrospective, I have done so much clumsy work in the past that could have been avoided by introducing proper value types for core domain concepts, like e.g. money, percentages, probabilities, etc.</p>
<p>I usually call myself &#8220;pretty domain-driven&#8221;, but now I realize that there&#8217;s an entire aspect of being just that, that I have overseen.</p>
<p>Do you think you&#8217;re domain-driven?</p>
]]></content:encoded>
			<wfw:commentRss>http://mookid.dk/oncode/archives/1359/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>I will be speaking about NoSQL and MongoDB</title>
		<link>http://mookid.dk/oncode/archives/1345</link>
		<comments>http://mookid.dk/oncode/archives/1345#comments</comments>
		<pubDate>Sun, 13 Jun 2010 15:50:07 +0000</pubDate>
		<dc:creator>mookid</dc:creator>
				<category><![CDATA[blablabla]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[nosql]]></category>

		<guid isPermaLink="false">http://mookid.dk/oncode/?p=1345</guid>
		<description><![CDATA[as seen from the eyes of a .NET developer at two events in June (in Danish). The first event is a JAOO Geek Night at Dong Energy in Skærbæk on Tuesday June 29th at 4:30 pm. You can read more about the free JAOO Geek Nights here. The other event is a meeting in Århus <a href='http://mookid.dk/oncode/archives/1345'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>as seen from the eyes of a .NET developer at two events in June (in Danish).</p>
<p>The <a href="https://secure.trifork.com/aarhus-2010/freeevent/index.jsp?eventOID=2631">first event</a> is a JAOO Geek Night at Dong Energy in Skærbæk on Tuesday June 29th at 4:30 pm. You can read more about the free JAOO Geek Nights <a href="http://jaoo.dk/aarhus-2010/upcomingevents/">here</a>.</p>
<p>The <a href="http://www.anug.dk/post/2010/06/08/Junimc3b8de-NoSQL-og-MongoDB.aspx">other event</a> is a meeting in <a href="http://www.anug.dk">Århus .NET User Group</a>, which is the day after, on Wednesday June 30th at 6 pm &#8211; you can sign up via Facebook <a href="http://www.facebook.com/#!/event.php?eid=123911754316166&#038;ref=ts">here</a>.</p>
<p>I&#8217;m really looking forward to it, because I think we will have some interesting discussions. And perhaps we can widen a few people&#8217;s horizons <img src='http://mookid.dk/oncode/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Hope to see a lot of engaged people at both events.</p>
]]></content:encoded>
			<wfw:commentRss>http://mookid.dk/oncode/archives/1345/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Big brownfield codebase, NDepend, and a Kaizen mind</title>
		<link>http://mookid.dk/oncode/archives/1052</link>
		<comments>http://mookid.dk/oncode/archives/1052#comments</comments>
		<pubDate>Wed, 02 Jun 2010 08:00:47 +0000</pubDate>
		<dc:creator>mookid</dc:creator>
				<category><![CDATA[code quality]]></category>
		<category><![CDATA[ndepend]]></category>

		<guid isPermaLink="false">http://mookid.dk/oncode/?p=1052</guid>
		<description><![CDATA[I have meant to write a post for quite a while now, on how my team and I got up and running with NDepend on a big legacy codebase. So, here goes: Preface I am currently employed as a developer on a mortgage bond administration system. The project was started almost 6 years ago when <a href='http://mookid.dk/oncode/archives/1052'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>I have meant to write a post for quite a while now, on how my team and I got up and running with NDepend on a big legacy codebase. So, here goes:</p>
<h4>Preface</h4>
<p>I am currently employed as a developer on a mortgage bond administration system. The project was started almost 6 years ago when SOA was (apparently!!) incredibly hot, so it&#8217;s got a lot of web services which was some architect&#8217;s interpretation of service-orientation.</p>
<p>The aforementioned &#8220;architect&#8221; left the project pretty early though, and after that our team has consisted of 4 to 8 people in various configurations.</p>
<p>This, combined with a couple of hectic deadlines along the way, has led to a big, fragmented codebase, where some areas have been left almost untouched for years, other areas are big balls of mud that everyone currently on the team fears to touch, other areas are characterized by developers having been in a hurry when they wrote the code etc etc.</p>
<p>A few times along the way, the idiomatic way of implementing new stuff has been radically changed to make things better. One example is that instead of orchestrating a bunch of web services RPC style, all new functionality is now being implemented in a single web service, messaging style.</p>
<p>Another thing is that the system is not built with an IoC container in mind, but that did not prevent us from introducing Castle Windsor. That means that services must be pulled from Windsor, service location style &#8211; and even though we try to encourage people to reduce their calls to the service locator in only a few well-defined places, some developers did not understand why, and they went ahead and used the locator in all kinds of places.</p>
<p>To put it like we do in Danish when someone owes more than their mortgage is worth: We have technical debt rising above our chimney!</p>
<h4>What to do?</h4>
<p>When you have so many problems that you don&#8217;t know where to begin, how do you solve your problems then? </p>
<p>Well, the Japanese have a word, <a href="http://en.wikipedia.org/wiki/Kaizen">Kaizen</a>, which is beautifully capturing the concept of constantly improving things.</p>
<p>It&#8217;s a philosophy I try to consider all day long, when I write code, modify code, and even when I look at code: I <em>constantly</em> make small changes, remove cruft, and refactor into better more idiomatic ways. How can I do that without <em>breaking</em> code as well? Simple: We have automated tests!</p>
<p><a href="http://www.ndepend.com/">NDepend</a> is a really cool tool that lets us achieve Kaizen on a higher level <img src='http://mookid.dk/oncode/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h4>Quick introduction if you don&#8217;t know anything at all about NDepend</h4>
<p>In NDepend, you create a project and add all the assemblies and .PDBs from your build. Now NDepend can analyze your assemblies and tell you all kinds of interesting stuff about your code.</p>
<p>E.g. it can show you a dependency matrix, which visualizes dependencies between assemblies and namespaces. That way, you can see if your application adheres to a layered structure, or if dependencies are circular.</p>
<p>But the feature I want to focus on here, is CQL rules. CQL is <em>Code Query Language</em>, which resembles SQL a bit, but is used to query assemblies, types, methods, fields etc. Using CQL, I can also generate warnings if certain conditions are not met.</p>
<p>What makes this extremely interesting in our case, is that we can run our CQL rules from our automated build, via CruiseControl.NET, which integrates nicely with the automatedness (is that a word?) that is required for an agile team.</p>
<h4>A few examples</h4>
<h5>Simple stuff &#8211; people not adhering to our naming conventions</h5>
<p>I am a firm believer that code must be clean, streamlined, and uniform, in order to reduce the perceived noise when reading it. For some reason, a couple of team members re-installed their ReSharper and got their R# naming rules reset, which resulted in numerous cases where field names were prefixed with <code>_</code>.</p>
<p>To address this annoyance, I created the following CQL warning:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"> WARN <span style="color: #993333; font-weight: bold;">IF</span> Count <span style="color: #66cc66;">&gt;</span> <span style="color: #cc66cc;">0</span> <span style="color: #993333; font-weight: bold;">IN</span> 
  <span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #993333; font-weight: bold;">FIELDS</span> <span style="color: #993333; font-weight: bold;">FROM</span> ASSEMBLIES 
    <span style="color: #ff0000;">&quot;SomeDomainAssembly.Core&quot;</span><span style="color: #66cc66;">,</span> 
    <span style="color: #ff0000;">&quot;SomeDomainAssembly.CoreServices&quot;</span><span style="color: #66cc66;">,</span> 
    <span style="color: #ff0000;">&quot;AnotherAssembly.Common&quot;</span><span style="color: #66cc66;">,</span> 
    <span style="color: #ff0000;">&quot;FourthAssembly.Foundation&quot;</span> 
  <span style="color: #993333; font-weight: bold;">WHERE</span> 
    NameLike <span style="color: #ff0000;">&quot;^_&quot;</span></pre></div></div>

<p>- which from now on will yield a warning and the names and locations of violations in the build report in CruiseControl.NET. Nifty!</p>
<h5>More annoying stuff &#8211; people using the service locator to instantiate stuff in tests!</h5>
<p>Building a pretty complex system with a complex domain can lead to complicated set ups when &#8220;unit&#8221; testing. E.g. when a payment is recorded in the system, a payment distributor will generate money transactions for interest, principal reduction, and more, in accordance with some particular customer&#8217;s strategy. Then, if the SUT needs a couple of payments to have been made, some of our developers took a shortcut in their test set ups, and just pulled a <code>IPaymentDistributor</code> from our service locator, which &#8211; unfortunately &#8211; is fully configured and functional in our tests.</p>
<p>The real problem is of course that a great portion of our core modules are so strongly coupled that they cannot be tested in isolation.</p>
<p>But given that we have 1 MLOC, it&#8217;s not feasible to change the design of our core module at this time. But what we <em>can</em> do, is to make it visible to developers when they pull stuff from the service locator during testing. That can be acieved with the following CQL:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;">WARN <span style="color: #993333; font-weight: bold;">IF</span> Count <span style="color: #66cc66;">&gt;</span> <span style="color: #cc66cc;">0</span> <span style="color: #993333; font-weight: bold;">IN</span> 
  <span style="color: #993333; font-weight: bold;">SELECT</span> TYPES <span style="color: #993333; font-weight: bold;">FROM</span> ASSEMBLIES 
    <span style="color: #ff0000;">&quot;SomeDomainAssembly.Core.Tests&quot;</span><span style="color: #66cc66;">,</span> 
    <span style="color: #ff0000;">&quot;SomeDomainAssembly.CoreServices.Tests&quot;</span>
  <span style="color: #993333; font-weight: bold;">WHERE</span> 
    IsDirectlyUsing <span style="color: #ff0000;">&quot;CoreStuff.ServiceLocator&quot;</span></pre></div></div>

<h5>Most annoying stuff &#8211; people not understanding IoC containers, using the service locator from within services already pulled from a container</h5>
<p>This is something, that makes me angry and sad at the same time <img src='http://mookid.dk/oncode/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  but some team members did not understand Castle Windsor and what IoC containers can do, so they just went on and did calls to <code>ServiceLocator.Resolve&lt;I...&gt;</code> <em>from within services that were already pulled from the container</em>.</p>
<p>There&#8217;s too many reasons that this is just icky, so I will just show the CQL that will make sure that this misconception will not live on:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;">WARN <span style="color: #993333; font-weight: bold;">IF</span> Count <span style="color: #66cc66;">&gt;</span> <span style="color: #cc66cc;">0</span> <span style="color: #993333; font-weight: bold;">IN</span>
  <span style="color: #993333; font-weight: bold;">SELECT</span> TYPES <span style="color: #993333; font-weight: bold;">FROM</span> ASSEMBLIES
    <span style="color: #ff0000;">&quot;SomeDomainAssembly.Core&quot;</span><span style="color: #66cc66;">,</span> 
    <span style="color: #ff0000;">&quot;SomeDomainAssembly.CoreServices&quot;</span><span style="color: #66cc66;">,</span> 
    <span style="color: #ff0000;">&quot;AnotherAssembly.Common&quot;</span><span style="color: #66cc66;">,</span> 
    <span style="color: #ff0000;">&quot;FourthAssembly.Foundation&quot;</span> 
  <span style="color: #993333; font-weight: bold;">WHERE</span> 
    HasAttribute <span style="color: #ff0000;">&quot;FourthAssembly.AutoRegistration.Attributes.ServiceAttribute&quot;</span>
    <span style="color: #993333; font-weight: bold;">AND</span> IsDirectlyUsing <span style="color: #ff0000;">&quot;CoreStuff.ServiceLocator&quot;</span></pre></div></div>

<p>As you can see, this rule builds on the fact that all our service registrations are made by registering types decorated with the <code>ServiceAttribute</code>.</p>
<h4>Conclusion</h4>
<p>I have shown a few examples on how we set up automated assertion of certain properties in our architecture. NDepend has already proven to be extremely useful for this kind of stuff, and it allows us to continually add rules whenever we identify problems, which is what we need.</p>
]]></content:encoded>
			<wfw:commentRss>http://mookid.dk/oncode/archives/1052/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Complexities</title>
		<link>http://mookid.dk/oncode/archives/1238</link>
		<comments>http://mookid.dk/oncode/archives/1238#comments</comments>
		<pubDate>Fri, 21 May 2010 20:41:32 +0000</pubDate>
		<dc:creator>mookid</dc:creator>
				<category><![CDATA[blablabla]]></category>
		<category><![CDATA[code quality]]></category>

		<guid isPermaLink="false">http://mookid.dk/oncode/?p=1238</guid>
		<description><![CDATA[Recently, I had the opportunity to teach an introductory course in programming in C#, including topics on dependency injection, IoC containers, and test-driven development. When I introduced the concept of dependency injection, and I suggested that this seemingly pretty simple and trivial task be accomplished by putting an IoC container to use, some of the <a href='http://mookid.dk/oncode/archives/1238'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Recently, I had the opportunity to teach an introductory course in programming in C#, including topics on dependency injection, IoC containers, and test-driven development.</p>
<p>When I introduced the concept of dependency injection, and I suggested that this seemingly pretty simple and trivial task be accomplished by putting an IoC container to use, some of the attendees reacted with scepticism and doubt &#8211; would this <em>thing</em>, configured with either endless fluent spells or &#8211; <em>shudder!</em> &#8211; tonnes of XML, not make everything even more complex?</p>
<p>At the time, I tried to convince them that an IoC container was cool, and that learning its ins and outs could be considered some kind of investment that &#8211; over time &#8211; would actually reduce complexity. This is not something new, and everybody who has ever used an IoC container will probably agree with me that this investment pays off. But still, I think I needed some words that would support my argument better.</p>
<p>So, here goes a few random thought about complexity&#8230;</p>
<h5>Complexity?</h5>
<p>Right now, I want to focus on the kind of complexity that is inherent in non-trivial programs. That is, the complexity can not be removed from the program. The complexity can be anything, really, and it is there in some form or another, and we need to deal with it.</p>
<h5>Immediate vs. deferred complexity</h5>
<p>Assuming we need to deal with it, how do we do it then? Which strategy do we follow? Well, acknowledging its existence is not the same as dealing with it, but it&#8217;s definitely a first step. Thereafter, we should probably consider either A) solving the complexity on a case-to-case ad hoc kind of basis, or B) building some kind of mechanism, that abstracts the identified complexity away, thus dealing with the complexity right now.</p>
<h5>Localized vs. dispersed complexity</h5>
<p>Definitely coupled to the above somehow, but not inseparable, is the localized vs. dispersed complexity question: When you identify some kind of complexity, do you A) solve the problem in all the little places where the complexity surfaces, or B) build some kind of framework that makes all the other code oblivious of the complexity?</p>
<h5>My opinion, and how it relates to IoC containers</h5>
<p>I don&#8217;t know about you, but I prefer B &#038; B: the abstraction and the framework. It might <a href="http://www.joelonsoftware.com/articles/LeakyAbstractions.html">leak</a>, and it might take some time for other developers to grok if they have never seen that particular problem solved like that before, but if the abstraction holds, it will probably assume some kind of pattern status that will be used, re-used, and recognized from then on.</p>
<p>The force of IoC containers is that they take control over object creation, thus providing hooks around whenever objects are created, and <em>object creation is an incredibly important event</em> in a running program. Having a hook in <em>that</em> proves to be infinitely useful (almost).</p>
<p>The IoC container solves the complexity of deciding <em>when</em> and <em>how</em> to create (<em>which</em>) objects. This would otherwise be a severely dispersed (spatially as well as temporally) complexity, or cross-cutting concern if you will, in that it is a really common thing to instantiate stuff and/or use existing instances of stuff, and the alternative would be to <code>new</code> up objects, maybe pulling from a cache somewhere, all around the place &#8211; thus infiltrating our program with our solution to that particular problem.</p>
<h5>Conclusion</h5>
<p>Use an IoC container. Learn to use its features. Allow the container to take responsibility. This will make you happy.</p>
<p>(seriously, do it! <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/1238/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
