<?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>Elegant Code &#187; Jarod Ferguson</title>
	<atom:link href="http://elegantcode.com/author/ferguson/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Fri, 10 Feb 2012 04:38:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.5</generator>
		<item>
		<title>Entity Framework 4.3 Released (Migrations)</title>
		<link>http://elegantcode.com/2012/02/09/entity-framework-4-3-released-migrations/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=entity-framework-4-3-released-migrations</link>
		<comments>http://elegantcode.com/2012/02/09/entity-framework-4-3-released-migrations/#comments</comments>
		<pubDate>Thu, 09 Feb 2012 21:24:23 +0000</pubDate>
		<dc:creator>Jarod Ferguson</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2012/02/09/entity-framework-4-3-released-migrations/</guid>
		<description><![CDATA[The EF team has released Entity Framework 4.3 which contains a fully supported version of Migrations. I have been using migrations in my projects since the Alpha 2 bits and would encourage EF Code First’ers to make the investment if they haven’t already. You can get EF 4.3 by installing the latest version of the [...]]]></description>
			<content:encoded><![CDATA[<p>The EF team has released Entity Framework 4.3 which contains a fully supported version of Migrations. I have been using migrations in my projects since the Alpha 2 bits and would encourage EF Code First’ers to make the investment if they haven’t already.</p>
<p>You can get EF 4.3 by installing the latest version of the <a href="http://nuget.org/packages/EntityFramework/">EntityFramework NuGet package</a>. </p>
<p>&#160;</p>
<p><a href="http://elegantcode.com/wp-content/uploads/2012/02/image.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2012/02/image_thumb.png" width="584" height="67" /></a></p>
<p>&#160;</p>
<h4>A summary of changes between 4.2 &amp; 4.3:</h4>
<ul>
<ul>
<li><em><strong>New Code First Migrations Feature. </strong>This is the primary new feature in EF 4.3 and allows a database created by Code First to be incrementally changed as your Code First model evolves. </em></li>
<li><em><strong>Removal of EdmMetadata table.</strong> If you allow Code First to create a database by simply running your application (i.e. without explicitly enabling Migrations) the creation will now take advantage of improvements to database schema generation we have implemented as part of Migrations. </em></li>
<li><em><strong>Bug fix for GetDatabaseValues.</strong> In earlier releases this method would fail if your entity classes and context were in different namespaces. This issue is now fixed and the classes don’t need to be in the same namespace to use GetDatabaseValues. </em></li>
<li><em><strong>Bug fix to support Unicode DbSet names.</strong> In earlier releases you would get an exception when running a query against a DbSet that contained some Unicode characters. This issue is now fixed. </em></li>
<li><em><strong>Data Annotations on non-public properties.</strong> Code First will not include private, protected, or internal properties by default. Even if you manually included these members in your model, using the Fluent API in previous versions of Code First would ignore any Data Annotations on these members. This is now fixed and Code First will process the Data Annotations once the private, protected, or internal properties are manually included in the model. </em></li>
<li><em><strong>More configuration file settings.</strong> We’ve enabled more Code First related settings to be specified in the App/Web.config file. This gives you the ability to set the default connection factory and database initializers from the config file. You can also specify constructor arguments to be used when constructing these objects. More details are available in the </em><a href="http://blogs.msdn.com/b/adonet/archive/2012/01/12/ef-4-3-configuration-file-settings.aspx"><em>EF 4.3 Configuration File Settings</em></a><em> blog post. </em></li>
</ul>
</ul>
<p>More details and walkthroughs are available over on the ADO.NET team blog <a href="http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-released.aspx">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2012/02/09/entity-framework-4-3-released-migrations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Solving the upload progress bar problem&#8211;The History of Node.js</title>
		<link>http://elegantcode.com/2012/02/06/solving-the-upload-progress-bar-problemthe-history-of-node-js/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=solving-the-upload-progress-bar-problemthe-history-of-node-js</link>
		<comments>http://elegantcode.com/2012/02/06/solving-the-upload-progress-bar-problemthe-history-of-node-js/#comments</comments>
		<pubDate>Mon, 06 Feb 2012 09:39:47 +0000</pubDate>
		<dc:creator>Jarod Ferguson</dc:creator>
				<category><![CDATA[Node.js]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2012/02/06/solving-the-upload-progress-bar-problemthe-history-of-node-js/</guid>
		<description><![CDATA[If you would have asked me how Node.js came to be I probably would have guessed something along the lines of a Stanford research lab. That is, until I stumbled across this youtube video ‘Ryan Dahl &#8211; History of Node.js’ from a Pheonix user group back in Oct 11. I intended to watch just a [...]]]></description>
			<content:encoded><![CDATA[<p>If you would have asked me how Node.js came to be I probably would have guessed something along the lines of a Stanford research lab. That is, until I stumbled across this youtube video <a href="http://www.youtube.com/watch?v=SAc0vQCC6UQ">‘Ryan Dahl &#8211; History of Node.js’</a> from a Pheonix user group back in Oct 11. I intended to watch just a few minutes, but it was really interesting and I ended up watching the whole thing. If you are into Node I recommend you check it out too.</p>
<p>A few points from the video:</p>
<ul>
<li>Ryan was working on a math PhD (Algebraic Topology), dropped out and moved to South America with no money </li>
<li>Ryan thinks Ruby has the most beautiful syntax, but all the assumptions about it are based on lies (Ruby is f*cked because it can only run on one thread) </li>
<li>Node was heavily influenced by Zed Shaw’s Mongrel. The idea that a webserver can be just a simple lib which does request/response (not necessarily a directory of files tied to file system) </li>
<li>Node was started trying to find the best way of notifying a user, real time, about the status of file upload over the web (who would have thought?) </li>
<li>The best thing about javascript on the server is that no one had used it. No way way to open a file, open a socket etc. This is good, because if there was, they would have done it wrong </li>
<li>Ryan quit his job and worked on node for 6 mos straight convinced it was ‘a thing’. Begged for a slot at JSConf in Berlin. Blew people away with an IRC chat server written in 400 lines of JS (had to demo on a different laptop and no idea if the demo would even work) </li>
<li>Some new up-and-coming node features like Node domains </li>
<li>Ryan and his team makes finger gestures and sound effects when talking about things like latency and load balancing <img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-winkingsmile" alt="Winking smile" src="http://elegantcode.com/wp-content/uploads/2012/02/wlEmoticon-winkingsmile.png" /> </li>
</ul>
<ul>Ryan tells a great story, and as with any great story comes great lessons. The ones that really struck home with me:</ul>
<ol>
<li>Sometimes you have to quit good things in order to achieve great things </li>
<li>The obvious solution to your problem might be right in front of your face </li>
</ol>
<ol></ol>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:5737277B-5D6D-4f48-ABFC-DD9C333F4C5D:91405c66-ede4-483b-bb59-395e049cafd6" class="wlWriterEditableSmartContent">
<div><object width="599" height="336"><param name="movie" value="http://www.youtube.com/v/SAc0vQCC6UQ?hl=en&amp;hd=1"></param><embed src="http://www.youtube.com/v/SAc0vQCC6UQ?hl=en&amp;hd=1" type="application/x-shockwave-flash" width="599" height="336"></embed></object></div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2012/02/06/solving-the-upload-progress-bar-problemthe-history-of-node-js/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>&#8220;Don&#8217;t be a meme, but a movement&#8221;</title>
		<link>http://elegantcode.com/2012/02/02/dont-be-a-meme-but-a-movement/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=dont-be-a-meme-but-a-movement</link>
		<comments>http://elegantcode.com/2012/02/02/dont-be-a-meme-but-a-movement/#comments</comments>
		<pubDate>Thu, 02 Feb 2012 20:51:10 +0000</pubDate>
		<dc:creator>Jarod Ferguson</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2012/02/02/dont-be-a-meme-but-a-movement/</guid>
		<description><![CDATA[Scott Hanselman wrote blog post earlier this year titled “Your Blog is The Engine of Community”, in which he encourages us to blog more, and tweet less. I hear you Scott. Social Media is junk food, and my brain is overweight! I used to have a healthy technical blog and really enjoyed contributing to the [...]]]></description>
			<content:encoded><![CDATA[<p>Scott Hanselman wrote blog post earlier this year titled <a href="http://www.hanselman.com/blog/YourBlogIsTheEngineOfCommunity.aspx">“Your Blog is The Engine of Community”</a>, in which he encourages us to blog more, and tweet less.</p>
<p>I hear you Scott.</p>
<p>Social Media is junk food, and my brain is overweight! I used to have a healthy technical blog and really enjoyed contributing to the community through writing. That was over 21 mos ago. Since then I have become a complacent retweeter (with occasional joke). Looking around at some of my favorite blogs, I can see many of you have fallen into the same trap (you know who you are).</p>
<p>Hey we all need a break, and that’s cool, but it’s time to start blogging again. Now don’t&#8217; run out and write one of those “My blog has been really quiet lately so this is the first post in an amazing series I am going to do” posts, because we all know how that one turns out. Instead, I just make an honest effort by writing one post, and have a good time doing it.</p>
<p>Scott shares some good pointers-</p>
<blockquote><p><em>“Blog your opinions. Blog your cool project, or your latest useful function or library. Don&#8217;t blog if it feels like work. Blog and get excited when someone comments. Often the comments are more fun and more useful than the post itself. <strong>Be passionate, but not rude.</strong> Point out failings, but suggest solutions. Organize. Invent.</em>“</p></blockquote>
<p>I have also started a personal blog over at <a href="http://jarodferguson.com">jarodferguson.com</a> where I am sharing my not-so-technical stuff. I have been meaning to do this for years. You know what? So far I really like it! It feels great because its <strong>MY</strong> content, <strong>MY</strong> brand. Twitter, Facebook, Path, Pinterest etc etc can take a back seat. Sure I will still enjoy them, but going forward I plan on doing a lot less ‘managing’ content across my networks. Blog first, social media site of the day second (besides Posterous makes it pretty easy to publish to all these other sites).</p>
<p>So how about you? Why not brush off that keyboard and share with us? You never know who might really enjoy your thoughts.</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2012/02/02/dont-be-a-meme-but-a-movement/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>SqlBulkCopy for Generic List&lt;T&gt; (useful for Entity Framework &amp; NHibernate)</title>
		<link>http://elegantcode.com/2012/01/26/sqlbulkcopy-for-generic-listt-useful-for-entity-framework-nhibernate/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=sqlbulkcopy-for-generic-listt-useful-for-entity-framework-nhibernate</link>
		<comments>http://elegantcode.com/2012/01/26/sqlbulkcopy-for-generic-listt-useful-for-entity-framework-nhibernate/#comments</comments>
		<pubDate>Fri, 27 Jan 2012 02:12:26 +0000</pubDate>
		<dc:creator>Jarod Ferguson</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://elegantcode.com/?p=4786</guid>
		<description><![CDATA[A common complaint of the Entity Framework is slow insert times for larger datasets. Last night I was trying to insert a catalog of 15k products and it was taking a very long time (I gave up after 5 minutes). I recalled this post a while back from Mikael Eliasson demonstrating SqlBulkCopy using .NET. I [...]]]></description>
			<content:encoded><![CDATA[<p>A common complaint of the Entity Framework is slow insert times for larger datasets. Last night I was trying to insert a catalog of 15k products and it was taking a very long time (I gave up after 5 minutes). I recalled this <a href="http://mikee.se/Archive.aspx/Details/using_the_sqlbulkcopy_to_batch_inserts_20111129">post</a> a while back from Mikael Eliasson demonstrating SqlBulkCopy using .NET. I had used BCP in SQL server, but not from .NET. I took Mikael’s example and roughed out a reusable generic version below, which produced 15k inserts in 2.4s or +- 6200 rows per second. I upped it to 4 catalogs, 224392 rows in 39s, for +- 5750 rps (changing between 4 files). These are pretty decent records too, 41 columns and a few of the fields have a meaty char count. Good enough I say.</p>
<p><code><div id="gist-1681480" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">public</span> <span class="k">static</span> <span class="k">void</span> <span class="n">BulkInsert</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;(</span><span class="kt">string</span> <span class="n">connection</span><span class="p">,</span> <span class="kt">string</span> <span class="n">tableName</span><span class="p">,</span> <span class="n">IList</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="n">list</span><span class="p">)</span></div><div class='line' id='LC2'><span class="p">{</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">using</span> <span class="p">(</span><span class="n">var</span> <span class="n">bulkCopy</span> <span class="p">=</span> <span class="k">new</span> <span class="n">SqlBulkCopy</span><span class="p">(</span><span class="n">connection</span><span class="p">))</span></div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">{</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">bulkCopy</span><span class="p">.</span><span class="n">BatchSize</span> <span class="p">=</span> <span class="n">list</span><span class="p">.</span><span class="n">Count</span><span class="p">;</span></div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">bulkCopy</span><span class="p">.</span><span class="n">DestinationTableName</span> <span class="p">=</span> <span class="n">tableName</span><span class="p">;</span></div><div class='line' id='LC7'><br/></div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">var</span> <span class="n">table</span> <span class="p">=</span> <span class="k">new</span> <span class="n">DataTable</span><span class="p">();</span></div><div class='line' id='LC9'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">var</span> <span class="n">props</span> <span class="p">=</span> <span class="n">TypeDescriptor</span><span class="p">.</span><span class="n">GetProperties</span><span class="p">(</span><span class="k">typeof</span><span class="p">(</span><span class="n">T</span><span class="p">))</span></div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="c1">//Dirty hack to make sure we only have system data types </span></div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="c1">//i.e. filter out the relationships/collections</span></div><div class='line' id='LC12'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">.</span><span class="n">Cast</span><span class="p">&lt;</span><span class="n">PropertyDescriptor</span><span class="p">&gt;()</span></div><div class='line' id='LC13'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">.</span><span class="n">Where</span><span class="p">(</span><span class="n">propertyInfo</span> <span class="p">=&gt;</span> <span class="n">propertyInfo</span><span class="p">.</span><span class="n">PropertyType</span><span class="p">.</span><span class="n">Namespace</span><span class="p">.</span><span class="n">Equals</span><span class="p">(</span><span class="s">&quot;System&quot;</span><span class="p">))</span></div><div class='line' id='LC14'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">.</span><span class="n">ToArray</span><span class="p">();</span></div><div class='line' id='LC15'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div><div class='line' id='LC16'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">foreach</span> <span class="p">(</span><span class="n">var</span> <span class="n">propertyInfo</span> <span class="k">in</span> <span class="n">props</span><span class="p">)</span></div><div class='line' id='LC17'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">{</span>             </div><div class='line' id='LC18'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">bulkCopy</span><span class="p">.</span><span class="n">ColumnMappings</span><span class="p">.</span><span class="n">Add</span><span class="p">(</span><span class="n">propertyInfo</span><span class="p">.</span><span class="n">Name</span><span class="p">,</span> <span class="n">propertyInfo</span><span class="p">.</span><span class="n">Name</span><span class="p">);</span></div><div class='line' id='LC19'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">table</span><span class="p">.</span><span class="n">Columns</span><span class="p">.</span><span class="n">Add</span><span class="p">(</span><span class="n">propertyInfo</span><span class="p">.</span><span class="n">Name</span><span class="p">,</span> <span class="n">Nullable</span><span class="p">.</span><span class="n">GetUnderlyingType</span><span class="p">(</span><span class="n">propertyInfo</span><span class="p">.</span><span class="n">PropertyType</span><span class="p">)</span> <span class="p">??</span> <span class="n">propertyInfo</span><span class="p">.</span><span class="n">PropertyType</span><span class="p">);</span></div><div class='line' id='LC20'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC21'><br/></div><div class='line' id='LC22'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">var</span> <span class="n">values</span> <span class="p">=</span> <span class="k">new</span> <span class="kt">object</span><span class="p">[</span><span class="n">props</span><span class="p">.</span><span class="n">Length</span><span class="p">];</span></div><div class='line' id='LC23'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">foreach</span> <span class="p">(</span><span class="n">var</span> <span class="n">item</span> <span class="k">in</span> <span class="n">list</span><span class="p">)</span></div><div class='line' id='LC24'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">{</span></div><div class='line' id='LC25'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">for</span> <span class="p">(</span><span class="n">var</span> <span class="n">i</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span> <span class="n">i</span> <span class="p">&lt;</span> <span class="n">values</span><span class="p">.</span><span class="n">Length</span><span class="p">;</span> <span class="n">i</span><span class="p">++)</span></div><div class='line' id='LC26'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">{</span></div><div class='line' id='LC27'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">values</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="p">=</span> <span class="n">props</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">GetValue</span><span class="p">(</span><span class="n">item</span><span class="p">);</span></div><div class='line' id='LC28'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC29'><br/></div><div class='line' id='LC30'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">table</span><span class="p">.</span><span class="n">Rows</span><span class="p">.</span><span class="n">Add</span><span class="p">(</span><span class="n">values</span><span class="p">);</span></div><div class='line' id='LC31'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC32'><br/></div><div class='line' id='LC33'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">bulkCopy</span><span class="p">.</span><span class="n">WriteToServer</span><span class="p">(</span><span class="n">table</span><span class="p">);</span></div><div class='line' id='LC34'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC35'><span class="p">}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1681480/94ccdef46951b9bb1953e41417301668a57efe98/gistfile1.cs" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1681480#file_gistfile1.cs" style="float:right;margin-right:10px;color:#666">gistfile1.cs</a>
            <a href="https://gist.github.com/1681480">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>
</code></p>
<p><code><span style="font-family: verdana">This works off just a basic list of items which property names match the table column names. Given that most POCO based ORM’s generally match the schema exactly, it works great with EF code first objects.</span></code></p>
<p><code><span style="font-family: verdana">To use I just build up a list of objects, pick the connection string off the DbContext and then call BulkInsert to save to the DB. Note that in this case I am just adding items to a List&lt;T&gt;, not the EF DbSet&lt;T&gt;.</span></code></p>
<p><code><div id="gist-1681888" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'>var imports = new List&lt;Product&gt;();</div><div class='line' id='LC2'>//Load up the imports</div><div class='line' id='LC3'><br/></div><div class='line' id='LC4'>//Pass in cnx, tablename, and list of imports</div><div class='line' id='LC5'>BulkInsert(context.Database.Connection.ConnectionString, &quot;Products&quot;, imports);</div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1681888/17c7489579af2a32c957f72f88396ab23d7f3b48/gistfile1.txt" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1681888#file_gistfile1.txt" style="float:right;margin-right:10px;color:#666">gistfile1.txt</a>
            <a href="https://gist.github.com/1681888">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>
</code></p>
<p><code><span style="font-family: verdana"></span></code></p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2012/01/26/sqlbulkcopy-for-generic-listt-useful-for-entity-framework-nhibernate/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>WAT</title>
		<link>http://elegantcode.com/2012/01/25/wat/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=wat</link>
		<comments>http://elegantcode.com/2012/01/25/wat/#comments</comments>
		<pubDate>Wed, 25 Jan 2012 19:32:29 +0000</pubDate>
		<dc:creator>Jarod Ferguson</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2012/01/25/wat/</guid>
		<description><![CDATA[Need a quick laugh? Of course you do! Watch this –&#62; A hilarious lightning talk by Gary Bernhardt from CodeMash 2012. Well done Gary, well done.]]></description>
			<content:encoded><![CDATA[<p>Need a quick laugh? Of course you do! Watch this –&gt; <a href="https://www.destroyallsoftware.com/talks/wat">A hilarious lightning talk by Gary Bernhardt from CodeMash 2012</a>.</p>
<p>Well done Gary, well done.</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2012/01/25/wat/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Resources for getting started with Backbone.js</title>
		<link>http://elegantcode.com/2012/01/23/resources-for-getting-started-with-backbone-js/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=resources-for-getting-started-with-backbone-js</link>
		<comments>http://elegantcode.com/2012/01/23/resources-for-getting-started-with-backbone-js/#comments</comments>
		<pubDate>Tue, 24 Jan 2012 05:34:43 +0000</pubDate>
		<dc:creator>Jarod Ferguson</dc:creator>
				<category><![CDATA[Backbone.js]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2012/01/23/resources-for-getting-started-with-backbone-js/</guid>
		<description><![CDATA[The current product I am building makes heavy use of HTML5 &#38; javascript to give the user a rich experience, both on and offline, across a variety of screens. Before I even started this application I knew I wanted a clean and proven approach to help manage the complexity on the client. After reviewing several [...]]]></description>
			<content:encoded><![CDATA[<p>The current product I am building makes heavy use of HTML5 &amp; javascript to give the user a rich experience, both on and offline, across a variety of screens. Before I even started this application I knew I wanted a clean and proven approach to help manage the complexity on the client. After reviewing several js frameworks I decided to go with backbone.js (<a href="http://addyosmani.github.com/todomvc/">compare yourself</a>). I have been working with backbone for several months and I am really happy with it, and would recommend to anyone building similar types of javascript applications.</p>
<p>As per the project description:</p>
<p><i>“</i><a href="http://github.com/documentcloud/backbone/"><i>Backbone</i></a><i> </i><i>supplies structure to JavaScript-heavy applications by providing <b>models </b>with key-value binding and custom events, <b>collections</b> with a rich API of enumerable functions, <b>views</b> with declarative event handling, and connects it all to your existing application over a RESTful JSON interface.”</i></p>
<p>There are a ton of good ‘getting started’ posts out there, so rather than duplicate those I thought I would put together a few of my favorite resources. Hopefully some of you might find them useful.</p>
<ul>
<li><a href="http://documentcloud.github.com/backbone/">Backbone.js</a> : The main github site- Here you will find valuable reference documentation as well a simple examples to introduce you to backbone. Be prepared to spend a little time here <img src='http://elegantcode.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  </li>
<li><a href="http://documentcloud.github.com/underscore/">Underscore.js</a> : “<i>It&#8217;s the tie to go along with <a href="http://docs.jquery.com/">jQuery</a></i><i>&#8216;s tux, and <a href="http://backbonejs.org/">Backbone.js</a></i><i>&#8216;s suspenders.”&#160; </i>If you haven&#8217;t heard about underscore do yourself a favor on go check it out. There is nothing magical about it, yet I can’t say enough. Even if you aren’t using backbone, I highly recommend this library (some folks are using it on the server with node.js as well). </li>
<li><a href="http://documentcloud.github.com/backbone/docs/todos.html">Todo.js</a> : A simple Todo list example using backbone.js </li>
<li><a href="http://addyosmani.github.com/todomvc/">TodoMVC</a> : Compare a truck load of JS MVC frameworks – <em>“a project which offers the same Todo application implemented using MVC concepts in most of the popular JavaScript MVC frameworks of today.”</em> </li>
<li><a href="https://github.com/addyosmani/backbone-fundamentals">Backbone.js Fundamentals</a> : A book on Backbone.js targeted at beginners and advanced users alike &#8211; by <a href="http://twitter.com/addyosmani">Addy Osmani</a> (and <a href="https://github.com/addyosmani/backbone-fundamentals/contributors">contributors</a>). This guide is quickly becoming the ‘mini-bible’ for backbone. Chalked full of nuggets, from beginning concepts to the more advanced. </li>
<li><a href="http://weblog.bocoup.com/introducing-the-backbone-boilerplate/">The Backbone Boilerplate</a> : <em>“Backbone Boilerplate is a set of best practices and utilities for building Backbone.js applications”</em> </li>
<li><a href="http://weblog.bocoup.com/organizing-your-backbone-js-application-with-modules/">Organizing Your Backbone.js Application With Modules</a> : Some guidance around how you might structure your application using modules (esp valuable for larger applications). </li>
<li><a href="http://backbonetutorials.com/organizing-backbone-using-modules/">Organizing your application using Modules (require.js)</a> : Similar to the previous article, but makes use of AMD &amp; Require.js to wire up the application. </li>
<li><a href="http://lostechies.com/derickbailey/category/backbone/">Derick Baileys blog on Lostechies</a> : Derick has been blogging on backbone for 6 mos or so. I appreciate reading Dericks blog because he has done such a good job of cataloging his experiences as he has learned the framework. When I found myself stumbling with backbone, my searches often led over to Dericks blog. </li>
<li><a href="http://joeybeninghove.com/2011/08/16/backbone-screencast-introduction-views/">Backbone.js Screencast &#8211; Introduction and Views</a> : A nice “<em>basic introduction on how to bootstrap a new Backbone.js application and go in-depth on how to use Backbone Views in particular”.</em> Joey now also has screencasts available over at his site <a href="http://backbonescreencasts.com/">http://backbonescreencasts.com/</a> </li>
<li><a href="http://www.youtube.com/watch?v=258gBoR734U">Backbone.js walkthrough of Models and Views (Part 1/2) Screencast :</a> Enough said! </li>
<li>Using node.js + backbone.js + socket.io for real-time goodness : I haven&#8217;t actually implemented this yet, but am excited about the <a href="http://blog.fogcreek.com/the-trello-tech-stack/">possibilities</a>. Check out <a href="http://developer.teradata.com/blog/jasonstrimpel/2011/11/backbone-js-and-socket-io">here</a> <a href="http://fzysqr.com/2011/02/28/nodechat-js-using-node-js-backbone-js-socket-io-and-redis-to-make-a-real-time-chat-app/">here</a> and <a href="http://andyet.net/blog/2011/feb/15/re-using-backbonejs-models-on-the-server-with-node/">here</a> for some examples. (seeing how the middle tier in this app is MVC.net, I may opt to swap socket.io for <a href="https://github.com/SignalR/SignalR">signalR</a>. Hoping to take the node.js plunge at some point). </li>
</ul>
<p><strong>Updated:</strong></p>
<ul>
<li><a href="http://backbonetraining.net/resources">http://backbonetraining.net/resources</a> : Excellent collection of resources</li>
<li><a href="http://recipeswithbackbone.com/">http://recipeswithbackbone.com/</a> : Strategies to accelerate development      <br />with Backbone.js ($24 e-book)</li>
</ul>
<p>That’s all for now. Please feel free to reach out with any other resources you found helpful and Ill add them on here. I am still very much learning and would love to read your posts. More to come-</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2012/01/23/resources-for-getting-started-with-backbone-js/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Social Media as a Software Development Tool?</title>
		<link>http://elegantcode.com/2010/04/01/social-media-as-a-software-development-tool/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=social-media-as-a-software-development-tool</link>
		<comments>http://elegantcode.com/2010/04/01/social-media-as-a-software-development-tool/#comments</comments>
		<pubDate>Fri, 02 Apr 2010 03:57:10 +0000</pubDate>
		<dc:creator>Jarod Ferguson</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/04/01/social-media-as-a-software-development-tool/</guid>
		<description><![CDATA[One thing about software development I have always struggled with is inter-team communication. As I develop, I am often thinking things like “I need to make sure I tell Elvis I moved this method” or “The team is really going to like the reduced friction of this new implementation”. I have used various methodologies to [...]]]></description>
			<content:encoded><![CDATA[<p>One thing about software development I have always struggled with is inter-team communication. As I develop, I am often thinking things like “I need to make sure I tell Elvis I moved this method” or “The team is really going to like the reduced friction of this new implementation”. I have used various methodologies to try and address this, most of which you have probably tried too:</p>
<ul>
<li>Detailed check-in notes (no one reads unless they are tracking down who broke something) </li>
<li>Code-reviews (*yawn*) </li>
<li>Stand-ups (wrong medium, too high level) </li>
<li>Pair programming (exclusive to 2 or 3 developers, and is too expensive to do at a high frequency) </li>
<li>IM (Too exclusive, temporary, can be distracting) </li>
<li>Shouting “Hey dude check this out” </li>
</ul>
<ul>All of these can be valuable, however none of them offer the signal to noise balance I am looking for. I want a mechanism which promotes and enables a different form of communication. So what about a form of social media? Wikipedia tells us:</ul>
<blockquote><p>“Social media is media designed to be disseminated through social interaction&#8230; Social media uses…technologies to transform and broadcast media monologues into social media dialogues. It supports the democratization of knowledge and information and transforms people from content consumers to content producers.”</p>
</blockquote>
<p>Personally I have gotten really adept at tracking and participating in twitter conversations, IM, email etc while I work. I am ready for a social client that lives in my development environment. A tool which enables me to informally talk to my team as I am writing code. </p>
<p>I have a bunch of ideas around what this could look like, and I think implemented properly it would make developing software better.</p>
<p>So is anyone out there doing anything like this? What sort of features would make it useful? </p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/04/01/social-media-as-a-software-development-tool/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Event Driven Architecture: Publishing Events using an IOC container</title>
		<link>http://elegantcode.com/2010/01/06/event-driven-architecture-publishing-events-using-an-ioc-container/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=event-driven-architecture-publishing-events-using-an-ioc-container</link>
		<comments>http://elegantcode.com/2010/01/06/event-driven-architecture-publishing-events-using-an-ioc-container/#comments</comments>
		<pubDate>Thu, 07 Jan 2010 00:29:27 +0000</pubDate>
		<dc:creator>Jarod Ferguson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Event Driven Architecture]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/01/06/event-driven-architecture-publishing-events-using-an-ioc-container/</guid>
		<description><![CDATA[In my last post I talked about advanced IOC usage and how it is possible to use an IOC container to resolve an open generic from a closed implementation. This is technically cool, but it does not explain why this is important. In this post I want to show some additional code that will demonstrate [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://elegantcode.com/2009/12/18/advanced-unity-connecting-implementations-to-open-generic-types/">my last post</a> I talked about advanced IOC usage and how it is possible to use an IOC container to resolve an open generic from a closed implementation. This is technically cool, but it does not explain why this is important. In this post I want to show some additional code that will demonstrate a basic concept of <a href="http://en.wikipedia.org/wiki/Event_Driven_Architecture">Event Driven Architecture</a>: Publishing an Event.</p>
<p>&#160;</p>
<h4>Why is Event Driven Architecture good?</h4>
<p>Event driven architecture is extremely extensible. <strong>In my mind, it the perfect solution to address the <a href="http://en.wikipedia.org/wiki/Open/closed_principle">Open Closed Principal</a> and enable <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single Responsibility</a> in code</strong>. </p>
<p>Consider a system that processes orders. There is a method called SubmitOrder(order) on an OrderController. It just validates and saves the new order to the database today.</p>
<p>In a following story, the product owner says “<strong>I need the system to send an email to the customer when the order is submitted</strong>”. No problem, inject the MailService into the OrderController, send the mail in the SubmitOrder(order) method. great.</p>
<p>The next story the product owner says “<strong>I need you to deduct the ordered quantities from the OnHand inventory</strong>”. Check, so we inject in the inventory service into our OrderController, and we call it from the SubmitOrder(order) method.</p>
<p>More stories…. the product owner says “<strong>We need to send a message to the warehouse fulfillment system to let them know a new order has been submitted</strong>” </p>
<p>Ugh, another service, another method. The tests for SubmitOrder become out of control. Even when extracting methods and encapsulating more logic into services, there is still violation of SRP &amp; OCP. Not to mention there could be performance degradation from performing all of these tasks synchronously while the user waits. </p>
<p><strong>Its not the job of SubmitOrder to do all of this, there has to be a better way.</strong></p>
<p>&#160;</p>
<h4>Publishing an Event Example</h4>
<p>What if I “<strong>tell</strong>” the system that an event had occurred, and anyone interested could take action? (like an old school observer right?) In the following code sample I am going to inject in an ‘EventPublisher’ into my OrderController, then use that object to notify the rest of the system by publishing an <a href="http://www.eaipatterns.com/EventMessage.html">event</a> using this line:</p>
<div>
<div class="csharpcode">
<pre class="alt">_eventPublisher.Publish(<span class="kwrd">new</span> OrderSubmittedEvent{OrderId = order.Id});</pre>
</p></div>
</div>
<h6>&#160;</h6>
<h6>The OrderController</h6>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> OrderController : Controller</pre>
<pre class="alteven">{</pre>
<pre class="alt">   <span class="kwrd">private</span> <span class="kwrd">readonly</span> IRepository&lt;Order&gt; _orderRepository;</pre>
<pre class="alteven">   <span class="kwrd">private</span> <span class="kwrd">readonly</span> IEventPublisher _eventPublisher;</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">   <span class="kwrd">public</span> OrderController(IRepository&lt;Order&gt; orderRepository, </pre>
<pre class="alt">                          IEventPublisher eventPublisher)</pre>
<pre class="alteven">   {</pre>
<pre class="alt">       _orderRepository = orderRepository;</pre>
<pre class="alteven">       _eventPublisher = eventPublisher;</pre>
<pre class="alt">   }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   <span class="kwrd">public</span> ActionResult SubmitOrder(OrderViewModel viewModel)</pre>
<pre class="alteven">   {</pre>
<pre class="alt">       <span class="kwrd">try</span></pre>
<pre class="alteven">       {</pre>
<pre class="alt">           <span class="kwrd">if</span> (ModelState.IsValid)</pre>
<pre class="alteven">           {</pre>
<pre class="alt">               var order = MapOrder(viewModel);</pre>
<pre class="alteven">               _orderRepository.Add(order);</pre>
<pre class="alt">               _orderRepository.SaveChanges();</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">               _eventPublisher.Publish(<span class="kwrd">new</span> OrderSubmittedEvent{OrderId = order.Id});</pre>
<pre class="alteven">             </pre>
<pre class="alt">               <span class="rem">//Display success message</span></pre>
<pre class="alteven">               <span class="rem">//ViewInfo.AddSuccessMessage(Language.SubmitOrderSuccess);</span></pre>
<pre class="alt">           }</pre>
<pre class="alteven">       }</pre>
<pre class="alt">       <span class="kwrd">catch</span></pre>
<pre class="alteven">       {</pre>
<pre class="alt">           ModelState.AddModelError(<span class="str">&quot;__Form&quot;</span>, Language.SubmitOrderError);</pre>
<pre class="alteven">       }</pre>
<pre class="alt">  </pre>
<pre class="alteven">       <span class="kwrd">return</span> View(viewModel);</pre>
<pre class="alt">   }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   <span class="rem">//other</span></pre>
<pre class="alteven">}</pre>
</p></div>
</div>
<p>&#160;</p>
<p>Now, using this simple <a href="http://www.eaipatterns.com/EventDrivenConsumer.html">Consumer</a> (Handler) interface:</p>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">interface</span> IConsumer&lt;T&gt;</pre>
<pre class="alteven">{</pre>
<pre class="alt">    <span class="kwrd">void</span> Handle(T eventMessage);</pre>
<pre class="alteven">}</pre>
</p></div>
</div>
<p>&#160;</p>
<p>I can independently implement each of the system requirements, as needed:</p>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> EmailOrderConfirmation : IConsumer&lt;OrderSubmittedEvent&gt;</pre>
<pre class="alteven">{</pre>
<pre class="alt">   <span class="kwrd">public</span> <span class="kwrd">void</span> Handle(OrderSubmittedEvent eventMessage)</pre>
<pre class="alteven">   {</pre>
<pre class="alt">      <span class="rem">//send email</span></pre>
<pre class="alteven">   }</pre>
<pre class="alt">}</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> NotifyWarehouse : IConsumer&lt;OrderSubmittedEvent&gt;</pre>
<pre class="alteven">{</pre>
<pre class="alt">   <span class="kwrd">public</span> <span class="kwrd">void</span> Handle(OrderSubmittedEvent eventMessage)</pre>
<pre class="alteven">   {</pre>
<pre class="alt">       <span class="rem">//notify warehouse</span></pre>
<pre class="alteven">   }</pre>
<pre class="alt">}</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> DeductOnHandInventory : IConsumer&lt;OrderSubmittedEvent&gt;</pre>
<pre class="alteven">{</pre>
<pre class="alt">   <span class="kwrd">public</span> <span class="kwrd">void</span> Handle(OrderSubmittedEvent eventMessage)</pre>
<pre class="alteven">   {</pre>
<pre class="alt">       <span class="rem">//deduct inventory</span></pre>
<pre class="alteven">   }</pre>
<pre class="alt">}</pre>
</p></div>
</div>
<p>&#160;</p>
<p>One of my favorite parts about this code: <strong>the container is building up all of these event consumers, which makes it is easy to satisfy all of the dependencies using constructor injection.</strong> This makes testing each of these handlers a breeze, and everything follows the same patterns and conventions keeping the code base understandable and clean. (Services, Controllers, Consumers all work the same)</p>
<p>Just plug in the dependencies in the EmailOrderConfirmation consumer ctor* like so:</p>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> EmailOrderConfirmation : IConsumer&lt;OrderSubmittedEvent&gt;</pre>
<pre class="alteven">{</pre>
<pre class="alt">   <span class="kwrd">private</span> <span class="kwrd">readonly</span> IRepository&lt;Order&gt; _orderRepository;</pre>
<pre class="alteven">   <span class="kwrd">private</span> <span class="kwrd">readonly</span> ISmtpService _smtpService;</pre>
<pre class="alt">   <span class="kwrd">private</span> <span class="kwrd">readonly</span> ILogger _logger;</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   <span class="kwrd">public</span> EmailOrderConfirmation(IRepository&lt;Order&gt; orderRepository, </pre>
<pre class="alteven">                                 ISmtpService smtpService,</pre>
<pre class="alt">                                 ILogger logger)</pre>
<pre class="alteven">   {</pre>
<pre class="alt">       _orderRepository = orderRepository;</pre>
<pre class="alteven">       _smtpService = smtpService;</pre>
<pre class="alt">       _logger = logger;</pre>
<pre class="alteven">   }</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">   <span class="kwrd">public</span> <span class="kwrd">void</span> Handle(OrderSubmittedEvent eventMessage)</pre>
<pre class="alt">   {</pre>
<pre class="alteven">       var order = _orderRepository.Single(x =&gt; x.Id == eventMessage.OrderId);</pre>
<pre class="alt">       var message = <span class="kwrd">new</span> SmtpMessage();</pre>
<pre class="alteven">       <span class="rem">//get customer info from order  &amp; populate message</span></pre>
<pre class="alt">       _smtpService.SendMessage(message);</pre>
<pre class="alteven">   }</pre>
<pre class="alt">}</pre>
</p></div>
</div>
<p><strong></strong></p>
<p><strong>* Note that you could also inject the IEventPublisher into a Consumer and publish more events. </strong></p>
<p><strong></strong></p>
<h4>&#160;</h4>
<h4>How Does it Work?</h4>
<p>Under the hood the IoC container is doing most of the work. It keeps track of the event subscriptions and also provides the consumer instantiation. </p>
<h5>Event Subscriptions</h5>
<p>Here is how the event subscriptions are added to the container. In this example I use an interface so that I can enable dependency injection into components, and then mock the GetSubscriptions&lt;T&gt; dependency for easy testing. I also use a static method for adding subscriptions since the registration process operation usually happens at bootstrapping time, which is generally all static. The IoC.Container here is thread safe. </p>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">interface</span> ISubscriptionService</pre>
<pre class="alteven">{</pre>
<pre class="alt">   IEnumerable&lt;IConsumer&lt;T&gt;&gt; GetSubscriptions&lt;T&gt;();</pre>
<pre class="alteven">}</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven"><span class="kwrd">public</span> <span class="kwrd">class</span> EventSubscriptions : ISubscriptionService</pre>
<pre class="alt">{</pre>
<pre class="alteven">   <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Add&lt;T&gt;()</pre>
<pre class="alt">   {</pre>
<pre class="alteven">       var consumerType = <span class="kwrd">typeof</span>(T);</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">       consumerType.GetInterfaces()</pre>
<pre class="alt">                   .Where(x =&gt; x.IsGenericType)</pre>
<pre class="alteven">                   .Where(x =&gt; x.GetGenericTypeDefinition() == <span class="kwrd">typeof</span>(IConsumer&lt;&gt;))</pre>
<pre class="alt">                   .ToList()</pre>
<pre class="alteven">                   .ForEach(x =&gt; IoC.Container.RegisterType(x, </pre>
<pre class="alt">                                                            consumerType, </pre>
<pre class="alteven">                                                            consumerType.FullName));</pre>
<pre class="alt">   }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   <span class="kwrd">public</span> IEnumerable&lt;IConsumer&lt;T&gt;&gt; GetSubscriptions&lt;T&gt;()</pre>
<pre class="alteven">   {</pre>
<pre class="alt">       var consumers =  IoC.Container.ResolveAll(<span class="kwrd">typeof</span>(IConsumer&lt;T&gt;));</pre>
<pre class="alteven">       <span class="kwrd">return</span> consumers.Cast&lt;IConsumer&lt;T&gt;&gt;();</pre>
<pre class="alt">   }</pre>
<pre class="alteven">}</pre>
</p></div>
</div>
<p>&#160;</p>
<h5>Event Publishing</h5>
<p>Now that the subscriptions are setup, the publisher can read those subscriptions, get the consumers from the container, and pass the event message instance to each of them. Again I am using an Interface so I can enable dependency injection (and mocking capabilities) for the components which need to do publishing (controllers, services)</p>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">interface</span> IEventPublisher</pre>
<pre class="alteven">{</pre>
<pre class="alt">   <span class="kwrd">void</span> Publish&lt;T&gt;(T eventMessage);</pre>
<pre class="alteven">}</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven"><span class="kwrd">public</span> <span class="kwrd">class</span> EventPublisher : IEventPublisher</pre>
<pre class="alt">{</pre>
<pre class="alteven">   <span class="kwrd">private</span> <span class="kwrd">readonly</span> ISubscriptionService _subscriptionService;</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">   <span class="kwrd">public</span> EventPublisher(ISubscriptionService subscriptionService)</pre>
<pre class="alt">   {</pre>
<pre class="alteven">       _subscriptionService = subscriptionService;</pre>
<pre class="alt">   }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   <span class="kwrd">public</span> <span class="kwrd">void</span> Publish&lt;T&gt;(T eventMessage)</pre>
<pre class="alteven">   {</pre>
<pre class="alt">       var subscriptions = _subscriptionService.GetSubscriptions&lt;T&gt;();</pre>
<pre class="alteven">       subscriptions.ToList().ForEach(x =&gt; PublishToConsumer(x, eventMessage));</pre>
<pre class="alt">   }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> PublishToConsumer&lt;T&gt;(IConsumer&lt;T&gt; x, T eventMessage)</pre>
<pre class="alteven">   {</pre>
<pre class="alt">       <span class="kwrd">try</span></pre>
<pre class="alteven">       {</pre>
<pre class="alt">           x.Handle(eventMessage);</pre>
<pre class="alteven">       }</pre>
<pre class="alt">       <span class="kwrd">catch</span>(Exception e)</pre>
<pre class="alteven">       {</pre>
<pre class="alt">           <span class="rem">//log and handle internally</span></pre>
<pre class="alteven">       }</pre>
<pre class="alt">       <span class="kwrd">finally</span></pre>
<pre class="alteven">       {</pre>
<pre class="alt">           var instance = x <span class="kwrd">as</span> IDisposable;</pre>
<pre class="alteven">           <span class="kwrd">if</span> (instance != <span class="kwrd">null</span>)</pre>
<pre class="alt">           {</pre>
<pre class="alteven">               instance.Dispose();</pre>
<pre class="alt">           }</pre>
<pre class="alteven">       }</pre>
<pre class="alt">   }</pre>
<pre class="alteven">}</pre>
</p></div>
</div>
<p>&#160;</p>
<p>- <strong>Keep in mind in this example is all running on the same thread, therefore even though semantically we are handling events as if they are asynchronous, it is a blocking operation</strong></p>
<p>&#160;</p>
<h4>Additional Benefits of this Architecture</h4>
<p>- Events are in messages, which can be serialized and processed on different threads, or even different nodes in a cluster. In a web environment, this might mean offloading the workload out of your IIS processes freeing web-server threads for performance &amp; scalability (see Service Bus section)</p>
<p>- Get multicast delegate observer like functionality without having to deal with static events, event registration &amp; deregistration (the whole += –= biz)</p>
<p>- Each event handler has its own class, each having 1 responsibility</p>
<p>- Very extensible, very maintainable (wait, I said that already?)</p>
<p>&#160;</p>
<h5></h5>
<h5></h5>
<h5></h5>
<h4>This is not a Service Bus</h4>
<p>This code above could work great in a simple MVC.NET application for implementing clean separation and structuring your code base into events. Though it gets a lot of influence from the OSS services busses, it is greatly simplified and merely demonstrates a simple concept of publishing &amp; consuming domain events using an IoC container.</p>
<p>A service bus does quite a bit more than just publishing local messages on single thread. If you find yourself enjoying this posts and want to take it to the next level, check out <a href="http://code.google.com/p/masstransit/">MassTransit</a> (Chris Patterson &amp; Dru Sellers) &amp; <a href="http://www.nservicebus.com/">nServiceBus</a> (Udi Dahan). I would also recommend the <a href="http://www.eaipatterns.com/eaipatterns.html">EAI patterns</a> books by Gregor Hohpe and recognize the <a href="http://www.eaipatterns.com/toc.html">reference patterns</a>. (one of these days Ill make it through it instead of using it for reference!)</p>
<p>Some additional concepts and common patterns you might find: </p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Publish/subscribe">Publish-Subscribe</a> </li>
<li><a href="http://en.wikipedia.org/wiki/Request-response">Request-Response</a> </li>
<li><a href="http://www.udidahan.com/2009/04/20/saga-persistence-and-event-driven-architectures/">Sagas (Workflow)</a> </li>
<li><a href="http://masstransit.pbworks.com/MessageCorrelation">Correlation</a> </li>
<li><a href="http://www.eaipatterns.com/CompetingConsumers.html">Competing Consumers</a> </li>
<li><a href="http://artofbabel.com/specials/73-distributed-processing-with-nservicebus.html">Distributed Load</a> (processing across many nodes in cluster) </li>
<li>Transport (Http, MSMQ, ActiveMq, WCF TCP) </li>
<li>Serialization (Binary, XML, JSON) </li>
<li>Threadpooling </li>
</ul>
<ul></ul>
<h4>The Specification</h4>
</p>
</p>
</p>
</p>
</p>
</p>
<p>Normally I don&#8217;t make a habit of testing the container, but in this case its so close to the container I feel its appropriate vs mocking out the subscriptions. Plus since this is a blog post demonstrating advanced IOC usage, I want explicitly show all of the dependencies required at bootstrap time.</p>
<p>Please note the LoggerSpy for assertions. In this spec we are really only concerned whether or not they get called. Because of the nature of eventing, using a <a href="http://xunitpatterns.com/Test%20Spy.html">Test Spy</a> is really the only good way I have found to assert whether or not your handlers get invoked. (<em>If your processing on multiple threads you will have to make sure they are all done before you check assertions, perhaps a future blog post)</em></p>
<div>
<div class="csharpcode">
<pre class="alt">[TestFixture]</pre>
<pre class="alteven"><span class="kwrd">public</span> <span class="kwrd">class</span> When_An_Order_Is_Submitted : Specification_Context</pre>
<pre class="alt">{</pre>
<pre class="alteven">   <span class="kwrd">private</span> LoggerSpy _loggerSpy;</pre>
<pre class="alt">   <span class="kwrd">private</span> Mock&lt;IRepository&lt;Order&gt;&gt; _orderRepositoryMock;</pre>
<pre class="alteven">   <span class="kwrd">readonly</span> IUnityContainer _container = IoC.Container;</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">   <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Context()</pre>
<pre class="alt">   {</pre>
<pre class="alteven">       <span class="rem">//setup EF repository mock</span></pre>
<pre class="alt">       _orderRepositoryMock = <span class="kwrd">new</span> Mock&lt;IRepository&lt;Order&gt;&gt;();</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">       <span class="rem">//logger spy to capture handler messages</span></pre>
<pre class="alteven">       _loggerSpy = <span class="kwrd">new</span> LoggerSpy();</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">       <span class="rem">//register with container</span></pre>
<pre class="alt">       _container.RegisterInstance&lt;ILogger&gt;(_loggerSpy);</pre>
<pre class="alteven">       _container.RegisterInstance(_orderRepositoryMock.Object);</pre>
<pre class="alt">       _container.RegisterType&lt;IEventPublisher, EventPublisher&gt;();</pre>
<pre class="alteven">       _container.RegisterType&lt;ISubscriptionService, EventSubscriptions&gt;();</pre>
<pre class="alt">       _container.RegisterType&lt;OrderController&gt;();</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">       <span class="rem">//add event subscriptions</span></pre>
<pre class="alteven">       EventSubscriptions.Add&lt;EmailOrderConfirmation&gt;();</pre>
<pre class="alt">       EventSubscriptions.Add&lt;NotifyWarehouse&gt;();</pre>
<pre class="alteven">       EventSubscriptions.Add&lt;DeductOnHandInventory&gt;();</pre>
<pre class="alt">   }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Because()</pre>
<pre class="alteven">   {</pre>
<pre class="alt">       _container.Resolve&lt;OrderController&gt;().SubmitOrder(<span class="kwrd">new</span> OrderViewModel());</pre>
<pre class="alteven">   }</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">   [Test]</pre>
<pre class="alt">   <span class="kwrd">public</span> <span class="kwrd">void</span> Order_Should_Be_Persisted()</pre>
<pre class="alteven">   {</pre>
<pre class="alt">       _orderRepositoryMock.Verify(x =&gt; x.Add(It.IsAny&lt;Order&gt;()));</pre>
<pre class="alteven">       _orderRepositoryMock.Verify(x =&gt; x.SaveChanges());</pre>
<pre class="alt">   }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   [Test]</pre>
<pre class="alteven">   <span class="kwrd">public</span> <span class="kwrd">void</span> Email_Notification_Should_Be_Sent_To_Customer()</pre>
<pre class="alt">   {</pre>
<pre class="alteven">       _loggerSpy.LoggedMessages.ShouldContain(Language.OrderConfirmationEmailSuccess);</pre>
<pre class="alt">   }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   [Test]</pre>
<pre class="alteven">   <span class="kwrd">public</span> <span class="kwrd">void</span> On_Hand_Inventory_Should_Be_Reduced()</pre>
<pre class="alt">   {</pre>
<pre class="alteven">       _loggerSpy.LoggedMessages.ShouldContain(Language.DeductOnHandInventorySuccess);</pre>
<pre class="alt">   }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   [Test]</pre>
<pre class="alteven">   <span class="kwrd">public</span> <span class="kwrd">void</span> Warehouse_Should_Be_Notified()</pre>
<pre class="alt">   {</pre>
<pre class="alteven">       _loggerSpy.LoggedMessages.ShouldContain(Language.NotifyWarehouseSuccess);</pre>
<pre class="alt">   }</pre>
<pre class="alteven">}</pre>
</p></div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/01/06/event-driven-architecture-publishing-events-using-an-ioc-container/feed/</wfw:commentRss>
		<slash:comments>37</slash:comments>
		</item>
		<item>
		<title>Advanced Unity: Connecting Implementations to Open Generic Types</title>
		<link>http://elegantcode.com/2009/12/18/advanced-unity-connecting-implementations-to-open-generic-types/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=advanced-unity-connecting-implementations-to-open-generic-types</link>
		<comments>http://elegantcode.com/2009/12/18/advanced-unity-connecting-implementations-to-open-generic-types/#comments</comments>
		<pubDate>Fri, 18 Dec 2009 23:46:47 +0000</pubDate>
		<dc:creator>Jarod Ferguson</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/18/advanced-unity-connecting-implementations-to-open-generic-types/</guid>
		<description><![CDATA[Jimmy Bogard has an excellent post called “Advanced StructureMap: connecting implementations to open generic types” which he uses the StructureMap IOC container to connect messages to handlers. This is something I have been using in my codebase to handle domain events, as well as a publish/subscribe mechanism for WCF message handling. I learned about this [...]]]></description>
			<content:encoded><![CDATA[<p>Jimmy Bogard has an excellent post called “<a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/12/17/advanced-structuremap-connecting-implementations-to-open-generic-types.aspx">Advanced StructureMap: connecting implementations to open generic types</a>” which he uses the <a href="http://structuremap.sourceforge.net/Default.htm">StructureMap</a> IOC container to connect messages to handlers. </p>
<p>This is something I have been using in my codebase to handle domain events, as well as a publish/subscribe mechanism for WCF message handling. I learned about this Handler&lt;T&gt;(or Consumer&lt;T&gt;) approach from the <a href="http://code.google.com/p/masstransit/wiki/MassTransit">MassTransit</a> codebase. For those that don&#8217;t know about MassTransit, it is lean service bus implementation for building loosely coupled applications using the .NET framework. I highly recommend checking it out.</p>
<p>Though I am a big fan of StructureMap, I have also use the <a href="http://www.codeplex.com/unity/">Unity dependency injection container</a> to resolve my handlers/consumers.</p>
<p>&#160;</p>
<h4>The Open Generic Handler</h4>
<p>As Jimmy described in his post, there is an generic interface describing a contract </p>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">interface</span> IHandler&lt;TEvent&gt; </pre>
<pre class="alteven">{</pre>
<pre class="alt">    <span class="kwrd">void</span> Handle(TEvent args);</pre>
<pre class="alteven">}</pre>
</p></div>
</div>
</p>
<h4>The Implementation</h4>
<p>The interface is implemented specifying the type (the Domain Event) for the interface contract</p>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> OrderCanceledEvent</pre>
<pre class="alteven">    : IHandler&lt;OrderCanceledMessage&gt;</pre>
<pre class="alt">{</pre>
<pre class="alteven">    <span class="kwrd">public</span> <span class="kwrd">void</span> Handle(OrderCanceledMessage args)</pre>
<pre class="alt">    {</pre>
<pre class="alteven">        <span class="rem">// send an email or something</span></pre>
<pre class="alt">    }</pre>
<pre class="alteven">}</pre>
</p></div>
</div>
<h4>Resolving the Handler</h4>
</p>
<p>When a given domain event occurs, the handler(s) is resolved for the given event, the “T”, or OrderCancelledMessage.</p>
<div>
<div class="csharpcode">
<pre class="alt">var handler = container.Resolve&lt;IHandler&lt;OrderCanceledMessage&gt;&gt;();</pre>
</p></div>
</div>
</p>
<h4>Configuring Unity</h4>
<p>There are a few ways to do this with Unity. I will show how to do it using a Unity Extension. Since this is fairly trivial, you could easily do it with a regular old Extension method, which would result in less setup code. </p>
<p>Basically the extension going to do is drill into the impl type and extract the interface that matches the passed in generic, and register it in the container. </p>
<h5>The Unity Extension</h5>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> OpenGenericExtension : UnityContainerExtension, IOpenGenericExtension</pre>
<pre class="alteven">{</pre>
<pre class="alt">    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Initialize()</pre>
<pre class="alteven">    {</pre>
<pre class="alt">       </pre>
<pre class="alteven">    }</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">    <span class="kwrd">public</span> <span class="kwrd">void</span> RegisterClosedImpl&lt;T&gt;(Type openGenericInterface)</pre>
<pre class="alt">    {</pre>
<pre class="alteven">        var closedType = <span class="kwrd">typeof</span>(T);</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">        closedType.GetInterfaces()</pre>
<pre class="alt">                  .Where(x =&gt; x.IsGenericType)</pre>
<pre class="alteven">                  .Where(x =&gt; x.GetGenericTypeDefinition() == openGenericInterface)</pre>
<pre class="alt">                  .ToList()</pre>
<pre class="alteven">                  .ForEach(x =&gt; Container.RegisterType(x, closedType));</pre>
<pre class="alt">    }</pre>
<pre class="alteven">}</pre>
</p></div>
</div>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">interface</span> IOpenGenericExtension : IUnityContainerExtensionConfigurator</pre>
<pre class="alteven">{</pre>
<pre class="alt">    <span class="kwrd">void</span> RegisterClosedImpl&lt;T&gt;(Type openInterface);</pre>
<pre class="alteven">}</pre>
</p></div>
</div>
<div>&#160;</div>
<h4>The Test</h4>
<p>Make it go.</p>
<div>
<div class="csharpcode">
<pre class="alt">[Test]</pre>
<pre class="alteven"><span class="kwrd">public</span> <span class="kwrd">void</span> should_connect_types()</pre>
<pre class="alt">{</pre>
<pre class="alteven">    var container = <span class="kwrd">new</span> UnityContainer();</pre>
<pre class="alt">    container.AddNewExtension&lt;OpenGenericExtension&gt;()</pre>
<pre class="alteven">             .Configure&lt;IOpenGenericExtension&gt;()</pre>
<pre class="alt">             .RegisterClosedImpl&lt;OrderCanceledEvent&gt;(<span class="kwrd">typeof</span>(IHandler&lt;&gt;));</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">    var handler = container.Resolve&lt;IHandler&lt;OrderCanceledMessage&gt;&gt;();</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">    Assert.AreEqual(handler.GetType(), <span class="kwrd">typeof</span>(OrderCanceledEvent));</pre>
<pre class="alteven">}</pre>
</p></div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/18/advanced-unity-connecting-implementations-to-open-generic-types/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Unity Extension for Entity Framework POCO Configuration, Repository and Unit of Work</title>
		<link>http://elegantcode.com/2009/12/15/building-a-unity-extension-for-entity-framework-poco-configuration-repository-and-unit-of-work/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=building-a-unity-extension-for-entity-framework-poco-configuration-repository-and-unit-of-work</link>
		<comments>http://elegantcode.com/2009/12/15/building-a-unity-extension-for-entity-framework-poco-configuration-repository-and-unit-of-work/#comments</comments>
		<pubDate>Wed, 16 Dec 2009 00:35:20 +0000</pubDate>
		<dc:creator>Jarod Ferguson</dc:creator>
				<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/15/building-a-unity-extension-for-entity-framework-poco-configuration-repository-and-unit-of-work/</guid>
		<description><![CDATA[In my previous two posts I talk about simple EF4 mappings and some common abstractions I like to work with for my entity persistence operations. In this post I want to take all of the setup code necessary for EF configuration and registration and encapsulate it along with the standard boiler plate IOC container code [...]]]></description>
			<content:encoded><![CDATA[<p>In my previous two posts I talk about <a href="http://elegantcode.com/2009/12/15/entity-framework-poco-ef4-a-simple-mapping/">simple EF4 mappings</a> and some <a href="http://elegantcode.com/2009/12/15/entity-framework-ef4-generic-repository-and-unit-of-work-prototype/">common abstractions</a> I like to work with for my entity persistence operations. In this post I want to take all of the setup code necessary for EF configuration and registration and encapsulate it along with the standard boiler plate IOC container code you might see in an application BootStrapper.</p>
<p>&#160;</p>
<h4>A Typical DI Example</h4>
<p>Though its pretty typical, I thought it would be good to show an example of how I expect to work with a Repository in my application. The “End Result” if you will.</p>
<p>The following is how one of my MVC.NET controllers might look (same for domain services, WCF services etc). Dependencies are satisfied via constructor injection when the controller or service is built up by the infrastructure (ControllerFactory or perhaps WCF IInstanceProvider).</p>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> RosterController</pre>
<pre class="alteven">{</pre>
<pre class="alt">   <span class="kwrd">private</span> <span class="kwrd">readonly</span> IRepository&lt;Team&gt; _teamRepository;</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   <span class="kwrd">public</span> RosterController(IRepository&lt;Team&gt; teamRepository)</pre>
<pre class="alteven">   {</pre>
<pre class="alt">       _teamRepository = teamRepository;</pre>
<pre class="alteven">   }</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">   <span class="kwrd">public</span> <span class="kwrd">void</span> AddNewPlayer(<span class="kwrd">long</span> teamId, <span class="kwrd">string</span> playerName, <span class="kwrd">string</span> position)</pre>
<pre class="alt">   {</pre>
<pre class="alteven">       var team = _teamRepository.First(x =&gt; x.ID == teamId);</pre>
<pre class="alt">       team.Players.Add(<span class="kwrd">new</span> Player{ Name = playerName, Position = position });</pre>
<pre class="alteven">   }</pre>
<pre class="alt">}</pre>
</p></div>
</div>
<p>In order to “wire up” the above example, there is quite a bit that has to happen. </p>
<p>&#160;</p>
<h4></h4>
<h4>The Unity Extension</h4>
<p>Unity provides extension points, called UnityContainerExtension’s which are a perfect place to handle IOC initialization for a given component. For those familiar with Castle Windsor facilities, its kind of like that (or StructureMap registries). </p>
<p>The EFRepositoryExtension (could probably use a better name?) handles:</p>
<ul>
<li>Creating the ContextBuilder and registering it with the Container </li>
<li>Registering the Generic Repository&lt;T&gt; and UnitOfWork </li>
<li>Context Lifetime </li>
<li>Entity Configuration &amp; EntitySet Registration </li>
<li>Context BuildUp </li>
</ul>
<p>The end result is nice clean extension I can register in my BootStrapper like so:</p>
<div>
<div class="csharpcode">
<pre class="alt">var container = IoC.Container; <span class="rem">//some static, thread safe container class</span></pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">container.AddNewExtension&lt;EFRepositoryExtension&gt;();</pre>
<pre class="alteven">container.Configure&lt;IEFRepositoryExtension&gt;()</pre>
<pre class="alt">         .WithConnection(cnxString)</pre>
<pre class="alteven">         .WithContextLifetime(<span class="kwrd">new</span> HttpContextLifetimeManager&lt;IObjectContext&gt;())</pre>
<pre class="alt">         .ConfigureEntity(<span class="kwrd">new</span> TeamConfiguration())</pre>
<pre class="alteven">         .ConfigureEntity(<span class="kwrd">new</span> PlayerConfiguration());</pre>
</p></div>
</div>
<div>A pretty nice API to work with if I get to say so <img src='http://elegantcode.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </div>
<div>&#160;</div>
<h5>Fluent Interface</h5>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">interface</span> IEFRepositoryExtension : IUnityContainerExtensionConfigurator</pre>
<pre class="alteven">{</pre>
<pre class="alt">    IEFRepositoryExtension WithConnection(<span class="kwrd">string</span> connectionString);</pre>
<pre class="alteven">    IEFRepositoryExtension WithContextLifetime(LifetimeManager lifetimeManager);</pre>
<pre class="alt">    IEFRepositoryExtension ConfigureEntity&lt;T&gt;(EntityConfiguration&lt;T&gt; config);</pre>
<pre class="alteven">    IEFRepositoryExtension ConfigureEntity&lt;T&gt;(EntityConfiguration&lt;T&gt; config, <span class="kwrd">string</span> setName);</pre>
<pre class="alt">}</pre>
</p></div>
</div>
<h5>Extension Implementation</h5>
<div>
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> EFRepositoryExtension : UnityContainerExtension, IEFRepositoryExtension</pre>
<pre class="alteven">{</pre>
<pre class="alt">  <span class="kwrd">private</span> ContextBuilder&lt;ObjectContext&gt; _builder;</pre>
<pre class="alteven">  <span class="kwrd">private</span> SqlConnection _connection;</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">  <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Initialize()</pre>
<pre class="alt">  {</pre>
<pre class="alteven">      _builder = <span class="kwrd">new</span> ContextBuilder&lt;ObjectContext&gt;();</pre>
<pre class="alt">      <span class="rem">//register the builder instance as a singleton, this will hold all of our </span></pre>
<pre class="alteven">      <span class="rem">//mapping information for the duration of our application as it creates </span></pre>
<pre class="alt">      <span class="rem">//new data contexts</span></pre>
<pre class="alteven">      Container.RegisterInstance(<span class="str">&quot;builder&quot;</span>, _builder, </pre>
<pre class="alt">                                 <span class="kwrd">new</span> ContainerControlledLifetimeManager());</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">      <span class="rem">//Register Repo &amp; UOW. Those these are transient instances, they both take</span></pre>
<pre class="alteven">      <span class="rem">//a ctor dependency on the ObjectContext which has its lifetime controlled</span></pre>
<pre class="alt">      <span class="rem">//by the Extension. E.g., for an Http current request, all repository and</span></pre>
<pre class="alteven">      <span class="rem">//UOW will use the same context/transaction</span></pre>
<pre class="alt">      Container.RegisterType(<span class="kwrd">typeof</span>(IRepository&lt;&gt;), <span class="kwrd">typeof</span>(Repository&lt;&gt;));</pre>
<pre class="alteven">      Container.RegisterType&lt;IUnitOfWork, UnitOfWork&gt;();</pre>
<pre class="alt">  }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">  <span class="kwrd">public</span> IEFRepositoryExtension WithConnection(<span class="kwrd">string</span> connectionString)</pre>
<pre class="alteven">  {</pre>
<pre class="alt">      _connection = <span class="kwrd">new</span> SqlConnection(connectionString);</pre>
<pre class="alteven">      <span class="kwrd">return</span> <span class="kwrd">this</span>;</pre>
<pre class="alt">  }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">  <span class="kwrd">public</span> IEFRepositoryExtension ConfigureEntity&lt;T&gt;(EntityConfiguration&lt;T&gt; config)</pre>
<pre class="alteven">  {</pre>
<pre class="alt">      <span class="rem">//simple pluralization of the entity set</span></pre>
<pre class="alteven">      ConfigureEntity(config, <span class="kwrd">typeof</span>(T).Name+<span class="str">&quot;s&quot;</span>);</pre>
<pre class="alt">      <span class="kwrd">return</span> <span class="kwrd">this</span>;</pre>
<pre class="alteven">  }</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">  <span class="kwrd">public</span> IEFRepositoryExtension ConfigureEntity&lt;T&gt;(EntityConfiguration&lt;T&gt; config, </pre>
<pre class="alt">                                                   <span class="kwrd">string</span> setName)</pre>
<pre class="alteven">  {</pre>
<pre class="alt">      <span class="rem">//add the configuration</span></pre>
<pre class="alteven">      _builder.Configurations.Add(config);</pre>
<pre class="alt">      <span class="rem">//register the set metadata</span></pre>
<pre class="alteven">      _builder.RegisterSet&lt;T&gt;(setName);</pre>
<pre class="alt">      <span class="kwrd">return</span> <span class="kwrd">this</span>;</pre>
<pre class="alteven">  }</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">  <span class="kwrd">public</span> IEFRepositoryExtension WithContextLifetime(LifetimeManager lifetimeManager)</pre>
<pre class="alt">  {</pre>
<pre class="alteven">      Container.AddNewExtension&lt;StaticFactoryExtension&gt;();</pre>
<pre class="alt">      Container.Configure&lt;IStaticFactoryConfiguration&gt;()</pre>
<pre class="alteven">               .RegisterFactory&lt;IObjectContext&gt;(x =&gt; </pre>
<pre class="alt">                   ContextResolver(x, lifetimeManager, _connection));</pre>
<pre class="alteven">      </pre>
<pre class="alt">      <span class="kwrd">return</span> <span class="kwrd">this</span>;</pre>
<pre class="alteven">  }</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">  <span class="rem">//factory func to build context with given lifetime &amp; connection</span></pre>
<pre class="alt">  <span class="kwrd">static</span> <span class="kwrd">readonly</span> Func&lt;IUnityContainer, LifetimeManager, SqlConnection, <span class="kwrd">object</span>&gt; </pre>
<pre class="alteven">      ContextResolver = (c, l, s) =&gt;</pre>
<pre class="alt">      {</pre>
<pre class="alteven">          var context = l.GetValue();</pre>
<pre class="alt">          <span class="kwrd">if</span> (context == <span class="kwrd">null</span>)</pre>
<pre class="alteven">          {</pre>
<pre class="alt">              var builder = c.Resolve&lt;ContextBuilder&lt;ObjectContext&gt;&gt;(<span class="str">&quot;builder&quot;</span>);</pre>
<pre class="alteven">              var newContext = builder.Create(s);</pre>
<pre class="alt">              context = <span class="kwrd">new</span> ObjectContextAdapter(newContext);</pre>
<pre class="alteven">              l.SetValue(context);</pre>
<pre class="alt">          }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">          <span class="kwrd">return</span> context;</pre>
<pre class="alteven">      };</pre>
<pre class="alt">}</pre>
</p></div>
</div>
<p>&#160;</p>
<h4>The Test</h4>
<p>Doing simple service location &amp; using TestLifetime, my prototype (not really a “test” I suppose)looks like:</p>
<div>
<div class="csharpcode">
<pre class="alt">var cnxString = ConfigurationManager.ConnectionStrings[<span class="str">&quot;Test&quot;</span>].ConnectionString;</pre>
<pre class="alteven">var container = IoC.Container; <span class="rem">//some static, thread safe container class</span></pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">container.AddNewExtension&lt;EFRepositoryExtension&gt;();</pre>
<pre class="alt">container.Configure&lt;IEFRepositoryExtension&gt;()</pre>
<pre class="alteven">&#160;&#160;&#160; .WithConnection(cnxString)</pre>
<pre class="alt">&#160;&#160;&#160; .WithContextLifetime(<span class="kwrd">new</span> TestLifetimeManager&lt;IObjectContext&gt;())</pre>
<pre class="alteven">&#160;&#160;&#160; .ConfigureEntity(<span class="kwrd">new</span> TeamConfiguration())</pre>
<pre class="alt">&#160;&#160;&#160; .ConfigureEntity(<span class="kwrd">new</span> PlayerConfiguration());</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">container.RegisterType&lt;RosterController&gt;();</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">var rosterController = container.Resolve&lt;RosterController&gt;();</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">rosterController.AddNewPlayer(3, <span class="str">&quot;Austin Collie&quot;</span>, <span class="str">&quot;&quot;</span>);</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">container.Resolve&lt;IUnitOfWork&gt;().Commit();</pre>
</p></div>
</div>
<p>&#160;</p>
<p>Thoughts and feedback are welcome.</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/15/building-a-unity-extension-for-entity-framework-poco-configuration-repository-and-unit-of-work/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

