<?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; Richard Cirerol</title>
	<atom:link href="http://elegantcode.com/author/rcirerol/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Thu, 02 Sep 2010 15:07:03 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Defining Development Experience</title>
		<link>http://elegantcode.com/2010/07/10/defining-development-experience/</link>
		<comments>http://elegantcode.com/2010/07/10/defining-development-experience/#comments</comments>
		<pubDate>Sat, 10 Jul 2010 07:21:32 +0000</pubDate>
		<dc:creator>Richard Cirerol</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/07/10/defining-development-experience/</guid>
		<description><![CDATA[Friday morning, one of my colleagues asked, “What do you consider to be the difference between a junior, mid-level, and senior developer?” 
Being a .NET shop, the obvious answer would be to head over to Scott Hanselman’s blog and pull up this post: What Great .NET Developers Ought To Know (More .NET Interview Questions).&#160; Scott [...]]]></description>
			<content:encoded><![CDATA[<p>Friday morning, one of my colleagues asked, “What do you consider to be the difference between a junior, mid-level, and senior developer?” </p>
<p>Being a .NET shop, the obvious answer would be to head over to Scott Hanselman’s blog and pull up this post: <a href="http://www.hanselman.com/blog/WhatGreatNETDevelopersOughtToKnowMoreNETInterviewQuestions.aspx">What Great .NET Developers Ought To Know (More .NET Interview Questions)</a>.&#160; Scott has broken out what he considered, at the time, to be the relevant platform- and framework-related knowledge required of a .NET developer at various points in their career.</p>
<p>However, I do not believe that knowledge of a programming language and hosting platform solely defines a great developer, no matter the depth or detail of the knowledge.&#160; If a developer is unable to apply that knowledge to a problem domain, it is useless knowledge – a mere parlor trick.</p>
<p>Given a developer has an affinity towards coding and technology, that developer should be able to learn new programming languages, new platforms, and new tools.&#160; If a senior developer in a ASP.NET shop moves to a Ruby shop, what would define him or her as a Senior level? Language syntax and idiomatics should only be a small part of the equation.</p>
<h4>&#160;</h4>
<h4>A Different Perspective</h4>
<p>I believe developer levels are determined by a combination of autonomy, mastery, and trust.&#160; I have a started a list below. This list is not scientific – it just represents my current viewpoint.</p>
<p>&#160;</p>
<h4>Junior Developers</h4>
<p>Autonomy: LOW</p>
<ul>
<li>Not self-directed </li>
<li>Need tasks rather than requirements/user stories</li>
<li>Tasks are expected to be implemented as defined</li>
<li>Often under the watchful eye of a senior developer</li>
<li>May need assistance in finding/deriving appropriate solutions</li>
</ul>
<p>Mastery: LOW-&gt;MEDIUM</p>
<ul>
<li>Comfortable with the constructs of their main language/platform</li>
<li>Basic understanding of object-oriented programming</li>
<li>May have understanding of architectural design patterns and principles (MVC, Single Responsibility Principle)</li>
<li>Limited comprehension of problem domain</li>
<li>Can write basic tests/specifications</li>
</ul>
<p>Trust: LOW </p>
<p>&#160;</p>
<h4>Mid-Level Developers</h4>
<p>Autonomy: MEDIUM</p>
<ul>
<li>Self-directed</li>
<li>Can work from user stories</li>
<li>Can normally find/derive appropriate solutions</li>
</ul>
<p>Mastery: MEDIUM</p>
<ul>
<li>Comfortable with the constructs of their main language and platform</li>
<li>Basic understanding of constructs of additional languages or platforms</li>
<li>Moderate understanding of object-oriented programming</li>
<li>Basic understanding of functional programming</li>
<li>Basic understanding of messaging architectures</li>
<li>Understands several design patterns and principles</li>
<li>Can write both state and interaction tests/specifications</li>
<li>Comprehends problem domain</li>
<li>Committed to continuous learning</li>
</ul>
<p>Trust: MEDIUM</p>
<ul>
<li>Can represent the needs of the development team</li>
<li>Is respected in the community</li>
</ul>
<h4>Senior Developers</h4>
<p>Autonomy: HIGH</p>
<ul>
<li>Self-directed</li>
<li>Can develop user stories</li>
<li>Can elucidate requirements</li>
<li>Can generally find, derive, or create appropriate solutions</li>
</ul>
<p>Mastery: MEDIUM-&gt;HIGH</p>
<ul>
<li>Comfortable with two or more languages/platforms</li>
<li>Moderate to high understanding of object-oriented and functional programming</li>
<li>Moderate to high understanding of messaging</li>
<li>Can explain design patterns and principles to developers, as well as non-technical staff</li>
<li>Comprehends problem domain and common domain patterns</li>
<li>Can write state, interaction, integration tests/specifications</li>
<li>Committed to continuous learning</li>
</ul>
<p>Trust: HIGH</p>
<ul>
<li>Can represent the needs of the development team</li>
<li>Can represent the needs of the customer</li>
<li>Can represent the needs of management</li>
<li>Is respected in the community</li>
</ul>
<p>Please note that I do have emphasis on language in each level, but language is dwarfed by the need to understand and communicate the problem domain.&#160; Also, mastery of a particular platform is less important than autonomy or trust.</p>
<p>What do you think defines a junior, mid, or senior developer?</p>
<p><script type="text/javascript">// <![CDATA[
  var cirerolGaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + cirerolGaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
// ]]&gt;</script><script type="text/javascript">// <![CDATA[
  var cirerolPageTracker = _gat._getTracker('UA-8257866-3'); cirerolPageTracker._initData(); cirerolPageTracker._trackPageview();
// ]]&gt;</script></p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/07/10/defining-development-experience/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Boise Code Camp 2010: Distributed Event-Driven Architecture Session Notes</title>
		<link>http://elegantcode.com/2010/03/28/boise-code-camp-2010-distributed-event-driven-architecture-session-notes/</link>
		<comments>http://elegantcode.com/2010/03/28/boise-code-camp-2010-distributed-event-driven-architecture-session-notes/#comments</comments>
		<pubDate>Sun, 28 Mar 2010 17:52:09 +0000</pubDate>
		<dc:creator>Richard Cirerol</dc:creator>
				<category><![CDATA[CodeCamp]]></category>
		<category><![CDATA[Event Driven Architecture]]></category>
		<category><![CDATA[Boise Code Camp 2010]]></category>
		<category><![CDATA[Message Bus]]></category>
		<category><![CDATA[NServiceBus]]></category>
		<category><![CDATA[Sample]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/03/28/boise-code-camp-2010-distributed-event-driven-architecture-session-notes/</guid>
		<description><![CDATA[I presented a session on event-driven architecture (with examples using NServiceBus) at Boise Code Camp yesterday.&#160; I had a great turnout and great feedback. Thanks so much to those who attended!&#160; 
If you attended and have any feedback/constructive criticism, please leave a comment!

For those who missed the session – or for those who would like [...]]]></description>
			<content:encoded><![CDATA[<p>I presented a session on event-driven architecture (with examples using NServiceBus) at Boise Code Camp yesterday.&#160; I had a great turnout and great feedback. Thanks so much to those who attended!&#160; </p>
<blockquote><p><strong>If you attended and have any feedback/constructive criticism, please leave a comment!</strong></p>
</blockquote>
<p>For those who missed the session – or for those who would like to see it again – you will get another opportunity. I will be presenting this session at <a href="http://www.netdug.com/" target="_blank">NETDUG</a> (in April, I believe).&#160; I am also submitting the session to <a href="http://portlandcodecamp.org" target="_blank">Portland Code Camp</a>.</p>
<h4>Session Assets</h4>
<p>As promised, I have included, in an <a href="http://code.google.com/p/codeprogression/source/browse/sample-projects/CodeProgression.BCC2010.zip" target="_blank">archive</a>:</p>
<ul>
<li>The slide deck</li>
<li>The solution as completed during the session (CodeProgression.BCC2010)</li>
</ul>
<p>I have also included:</p>
<ul>
<li>The solution with which we started (CodeProgression.BCC2010.Start)</li>
<li>A solution based on a MassTransit sample (from which I based the NServiceBus sample)</li>
</ul>
<blockquote><p><strong>Notes about the solutions:</strong></p>
<p>If you are planning on working the NServiceBus sample from scratch, don’t forget to add the NServiceBus.Host.exe as the startup program for each endpoint project.</p>
<p>For the MassTransit solution, you may need to update the <em>references\masstransit\MassTransit.RuntimeServices.exe.config</em> to point to your local database.</p>
</blockquote>
<p>&#160;</p>
<h4>Resources</h4>
<p>Here is also a list of resources I used while preparing for this session:</p>
<p><strong><u>NServiceBus       <br /></u></strong><a href="http://www.nservicebus.com">http://www.nservicebus.com</a>    <br /><a href="http://gurustop.net/blog/2008/04/20/enterprise-service-bus-messaging-using-nservicebus/">http://gurustop.net/blog/2008/04/20/enterprise-service-bus-messaging-using-nservicebus/</a>    <br /><a href="http://elegantcode.com/2009/10/09/exploring-nservicebus/">http://elegantcode.com/2009/10/09/exploring-nservicebus/</a>    <br /><a href="http://sourceforge.net/apps/mediawiki/nservicebus/index.php?title=Tutorials">http://sourceforge.net/apps/mediawiki/nservicebus/index.php?title=Tutorials</a>    <br /><a href="http://blog.zoolutions.se/post/2010/02/08/Conquering-NServiceBus-part-1-e28093-Getting-Started.aspx">http://blog.zoolutions.se/post/2010/02/08/Conquering-NServiceBus-part-1-e28093-Getting-Started.aspx</a>    <br /><a href="http://blog.zoolutions.se/post/2010/02/09/Conquering-NServiceBus-part-2-e28093-Initial-configuration.aspx">http://blog.zoolutions.se/post/2010/02/09/Conquering-NServiceBus-part-2-e28093-Initial-configuration.aspx</a></p>
<p><strong><u>MassTransit       <br /></u></strong><a href="http://masstransit.pbworks.com/A-First-Look-at-Mass-Transit">http://masstransit.pbworks.com/A-First-Look-at-Mass-Transit</a>    <br /><a href="http://blogs.dovetailsoftware.com/blogs/kmiller/archive/2009/08/26/producing-and-consuming-messages-using-masstransit-and-structuremap.aspx">http://blogs.dovetailsoftware.com/blogs/kmiller/archive/2009/08/26/producing-and-consuming-messages-using-masstransit-and-structuremap.aspx</a>    <br /><a href="http://rhysc.blogspot.com/2009/05/getting-started-with-masstransit.html">http://rhysc.blogspot.com/2009/05/getting-started-with-masstransit.html</a></p>
<p><strong><u>TopShelf       <br /></u></strong><a href="http://blogs.dovetailsoftware.com/blogs/kmiller/archive/2010/01/20/configuring-topshelf-using-a-structuremap-container.aspx">http://blogs.dovetailsoftware.com/blogs/kmiller/archive/2010/01/20/configuring-topshelf-using-a-structuremap-container.aspx</a>    <br /><a href="http://blogs.dovetailsoftware.com/blogs/kmiller/archive/2010/01/20/controlling-application-lifetime-in-topshelf.aspx">http://blogs.dovetailsoftware.com/blogs/kmiller/archive/2010/01/20/controlling-application-lifetime-in-topshelf.aspx</a></p>
<p><strong><u>Misc       <br /></u></strong><a href="http://www.enterpriseintegrationpatterns.com">http://www.enterpriseintegrationpatterns.com</a>    <br /><a href="http://www.enterpriseintegrationpatterns.com/ramblings/18_starbucks.html">http://www.enterpriseintegrationpatterns.com/ramblings/18_starbucks.html</a>    <br /><a href="http://www.amazon.com/Enterprise-Integration-Patterns-Designing-Deploying/dp/0321200683">http://www.amazon.com/Enterprise-Integration-Patterns-Designing-Deploying/dp/0321200683</a></p>
<p><script type="text/javascript">// <![CDATA[
  var cirerolGaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + cirerolGaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
// ]]&gt;</script><script type="text/javascript">// <![CDATA[
  var cirerolPageTracker = _gat._getTracker('UA-8257866-3'); cirerolPageTracker._initData(); cirerolPageTracker._trackPageview();
// ]]&gt;</script></p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/03/28/boise-code-camp-2010-distributed-event-driven-architecture-session-notes/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Is MSpec an Internal DSL?&#8230;And is that okay?</title>
		<link>http://elegantcode.com/2010/03/03/is-mspec-an-internal-dsland-is-that-okay/</link>
		<comments>http://elegantcode.com/2010/03/03/is-mspec-an-internal-dsland-is-that-okay/#comments</comments>
		<pubDate>Wed, 03 Mar 2010 20:27:07 +0000</pubDate>
		<dc:creator>Richard Cirerol</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[Internal DSL]]></category>
		<category><![CDATA[MSpec]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/03/03/is-mspec-an-internal-dsland-is-that-okay/</guid>
		<description><![CDATA[In my last post on MSpec, John Sonmez commented:
When I see the MSpec code, I think about it being an internal DSL for doing the testing, and I start to think that perhaps it should just go ahead and be it’s own language instead of trying to live inside of C#. On the other hand, [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://codeprogression.blogspot.com/2010/03/evolution-of-test-specification-styles.html">last post</a> on MSpec, <a href="http://elegantcode.com/2010/03/01/an-evolution-of-test-specification-styles-my-journey-to-mspec/#comment-54161">John Sonmez commented</a>:</p>
<blockquote><p>When I see the MSpec code, I think about it being an internal DSL for doing the testing, and I start to think that perhaps it should just go ahead and be it’s own language instead of trying to live inside of C#. On the other hand, I wonder about the value of using another language to unit test C# code…</p></blockquote>
<p>I think John was spot-on with his instinct – in my opinion, MSpec is an internal DSL.  I also think that is the beauty of the framework.  Domain-specific languages are meant to solve a target problem in a particular domain.  MSpec’s problem domain is testing .NET code.  By convention, it constrains you to its limited language to help you test your code in a meaningful yet powerful manner.</p>
<h4>What is an Internal DSL?</h4>
<p>According to Martin Fowler:</p>
<blockquote><p>“Internal DSLs are particular ways of using a host language to give the host language the feel of a particular language&#8230;Internal DSLs are also referred to as embedded DSLs or FluentInterfaces”  (from Bliki article: <a href="http://www.martinfowler.com/bliki/DomainSpecificLanguage.html" target="_blank">Domain Specific Language</a>)</p>
<p>“Internal DSLs use the same general purpose programming language that the wider application uses, but uses that language in a particular and limited style.”<br />
(from DSL-WIP section: <a href="http://martinfowler.com/dslwip/UsingDsls.html#DefiningDomainSpecificLanguages" target="_blank">Using Domain Specific Languages</a>)</p></blockquote>
<p><strong>But, as John wondered, <em>is there value in using another language (external DSL) to test C# code?</em> </strong></p>
<p>Perhaps.  Yet, I believe there is more value in using external DSLs to test user interfaces (e.g., <a href="http://watir.com/" target="_blank">WatiR</a>, <a href="http://watin.sourceforge.net/" target="_blank">WatiN</a>, and <a href="http://seleniumhq.org/" target="_blank">Selenium</a>), or for build scripting (e.g.,<a href="http://rake.rubyforge.org/" target="_blank">Rake</a>, <a href="http://code.google.com/p/psake/" target="_blank">psake</a>).</p>
<p><strong>Let’s look at that question a little differently:<em> Is there value in using an internal DSL (like MSpec) to test C# code?</em></strong></p>
<p>To that I give a resounding YES! MSpec’s host language is C#…which provides great value to me.  I get all the benefits of intellisense, refactoring, and (R#) navigation in my IDE.  I don’t have to worry about the impedance mismatch between my code and an external DSL.</p>
<h4>You Probably Use DSLs All the Time</h4>
<p>In fact, I use several DSLs every day when I code.</p>
<p>Consider the following table of frameworks. You may not have thought any of these in the context of a domain-specific language, but each has a specific purpose with its own limited language constructs. Some are internal, some external.</p>
<table border="1" cellspacing="0" cellpadding="2" width="541">
<tbody>
<tr>
<td width="128" valign="top"><strong>DSL</strong></td>
<td width="90" valign="top"><strong>Type</strong></td>
<td width="124" valign="top"><strong>Host Language</strong></td>
<td width="197" valign="top"><strong>Problem Domain</strong></td>
</tr>
<tr>
<td width="133" valign="top"><a href="http://structuremap.sourceforge.net/" target="_blank">StructureMap</a></td>
<td width="97" valign="top">Internal</td>
<td width="124" valign="top">C#</td>
<td width="193" valign="top">Dependency injection<br />
Inversion of control</td>
</tr>
<tr>
<td width="135" valign="top"><a href="http://www.codeplex.com/AutoMapper" target="_blank">AutoMapper</a></td>
<td width="100" valign="top">Internal</td>
<td width="123" valign="top">C#</td>
<td width="192" valign="top">Object-to-object mapping</td>
</tr>
<tr>
<td width="135" valign="top"><a href="http://www.ayende.com/projects/rhino-mocks.aspx" target="_blank">RhinoMocks</a></td>
<td width="102" valign="top">Internal</td>
<td width="123" valign="top">C#</td>
<td width="191" valign="top">Proxy object interaction and verification</td>
</tr>
<tr>
<td width="135" valign="top"><a href="http://code.google.com/p/moq/" target="_blank">Moq</a></td>
<td width="103" valign="top">Internal</td>
<td width="123" valign="top">C#</td>
<td width="191" valign="top">Proxy object interaction and verification</td>
</tr>
<tr>
<td width="135" valign="top"><a href="http://jquery.com/" target="_blank">jQuery</a></td>
<td width="103" valign="top">Internal</td>
<td width="123" valign="top">JavaScript</td>
<td width="191" valign="top">Document traversal<br />
Event handling<br />
Animation</td>
</tr>
<tr>
<td width="135" valign="top"><a href="http://www.w3.org/Style/CSS/" target="_blank">Cascading Style Sheets</a></td>
<td width="103" valign="top">External</td>
<td width="123" valign="top">English</td>
<td width="191" valign="top">Presentation semantics</td>
</tr>
<tr>
<td width="135" valign="top"><a href="http://rake.rubyforge.org/" target="_blank">Rake</a></td>
<td width="103" valign="top">External</td>
<td width="123" valign="top">Ruby</td>
<td width="191" valign="top">Build/task automation</td>
</tr>
<tr>
<td width="135" valign="top"><a href="http://code.google.com/p/psake/" target="_blank">psake</a></td>
<td width="103" valign="top">External</td>
<td width="123" valign="top">PowerShell</td>
<td width="191" valign="top">Build/task automation</td>
</tr>
<tr>
<td width="135" valign="top"><a href="http://nant.sourceforge.net/" target="_blank">nAnt</a></td>
<td width="103" valign="top">External</td>
<td width="123" valign="top">XML</td>
<td width="191" valign="top">Build/task automation</td>
</tr>
<tr>
<td width="135" valign="top"><a href="http://en.wikipedia.org/wiki/SQL" target="_blank">SQL</a></td>
<td width="103" valign="top">External</td>
<td width="123" valign="top">English</td>
<td width="191" valign="top">Data management</td>
</tr>
<tr>
<td width="135" valign="top"><a href="http://cukes.info/" target="_blank">Cucumber</a></td>
<td width="103" valign="top">External</td>
<td width="123" valign="top">Gherkin</td>
<td width="191" valign="top">Behavior-driven development</td>
</tr>
</tbody>
</table>
<p>When considering a framework within your host language: If the framework has a fluent interface with language devoted to a specific problem domain, it is probably an internal DSL.</p>
<p>So is MSpec an internal DSL? Yes.</p>
<p>And is that okay? Definitely.</p>
<h4>Further Reading</h4>
<p>Check out Martin Fowler’s articles on domain-specific languages:</p>
<p><a href="http://www.martinfowler.com/bliki/DomainSpecificLanguage.html">http://www.martinfowler.com/bliki/DomainSpecificLanguage.html</a><br />
<a href="http://martinfowler.com/dslwip/UsingDsls.html">http://martinfowler.com/dslwip/UsingDsls.html</a><br />
<a href="http://martinfowler.com/dslwip/InternalOverview.html">http://martinfowler.com/dslwip/InternalOverview.html</a></p>
<p><script type="text/javascript">// <![CDATA[
  var cirerolGaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + cirerolGaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
// ]]&gt;</script><script type="text/javascript">// <![CDATA[
  var cirerolPageTracker = _gat._getTracker('UA-8257866-3'); cirerolPageTracker._initData(); cirerolPageTracker._trackPageview();
// ]]&gt;</script></p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/03/03/is-mspec-an-internal-dsland-is-that-okay/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>An Evolution of Test-Specification Styles &#8211; My Journey to MSpec</title>
		<link>http://elegantcode.com/2010/03/01/an-evolution-of-test-specification-styles-my-journey-to-mspec/</link>
		<comments>http://elegantcode.com/2010/03/01/an-evolution-of-test-specification-styles-my-journey-to-mspec/#comments</comments>
		<pubDate>Tue, 02 Mar 2010 03:32:57 +0000</pubDate>
		<dc:creator>Richard Cirerol</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[MSpec]]></category>
		<category><![CDATA[NUnit]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/03/01/an-evolution-of-test-specification-styles-my-journey-to-mspec/</guid>
		<description><![CDATA[Over the last few years, the practice of Test-Driven Design and Behavior-Driven Design has increased in acceptance, even if its practice has not increased in equal proportion.&#160; From my perspective, specification-based design is a natural way to develop software.&#160; Each developer has a preferred framework, and a framework they loathe.&#160; In the .NET world, there [...]]]></description>
			<content:encoded><![CDATA[<p>Over the last few years, the practice of Test-Driven Design and Behavior-Driven Design has increased in acceptance, even if its practice has not increased in equal proportion.&#160; From my perspective, specification-based design is a natural way to develop software.&#160; Each developer has a preferred framework, and a framework they loathe.&#160; In the .NET world, there are a plethora of unit testing frameworks &#8211; NUnit has been nearly ubiquitous; mbUnit was evolutionary; xUnit was revolutionary; MSTest is…er, getting an update.&#160; For BDD, you can find frameworks like SpecUnit.NET, NBehave, and MSpec.&#160; My current framework of choice is MSpec, especially when <a href="http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/" target="_blank">coupled with StructureMap’s automocking container and a couple helper classes</a>. </p>
<p>From my unscientific observation, developers either love or hate MSpec.&#160; For those that hate MSpec, I wonder if it is the grammatical syntax or the lambda-expression style creating the aversion.&#160; Some even expound MSpec as cryptic and cumbersome.&#160; This seems to be a common complaint – one I hope to address in this post.</p>
<p>I find that those drawn to MSpec have experienced an evolution of testing/specification styles, influenced partially by the community and partially by frameworks they have used.&#160; At the very least, this has been my experience as I have transitioned from xUnit frameworks. </p>
<h4>Conventions of MSpec</h4>
<p>I particularly like the conventions MSpec encourages using its four delegate types:</p>
<p><strong>Establish</strong>: </p>
<ul>
<li>Provides setup (context) for the specification </li>
<li>One per class (but not required) </li>
<li>“Unlimited” per specification or inheritance chain </li>
<li>Runs down the inheritance chain prior to the <strong>Because</strong> delegate </li>
</ul>
<p><strong>Because</strong>:</p>
<ul>
<li>The action/event being tested </li>
<li>One per specification </li>
</ul>
<p><strong>It</strong>: </p>
<ul>
<li>An assertion (usually extension methods/fluent interfaces based on NUnit/xUnit Assert classes) </li>
<li>“Unlimited” per specification/class </li>
<li>Can be “hosted” in a <strong>Behavior</strong> class </li>
<li>Runs after the <strong>Because</strong> </li>
<li>Can be reused when placed in a <strong>Behavior</strong> class </li>
<li>If body of delegate is missing, will mark as “Ignored” or “Not Implemented” in a test runner </li>
</ul>
<p><strong>Cleanup</strong>:</p>
<ul>
<li>Provides teardown for the specification </li>
<li>One per class (but not required) </li>
<li>“Unlimited” per specification or inheritance chain </li>
<li>Runs up the inheritance chain after the <strong>It</strong> delegates are completed </li>
</ul>
<p>MSpec also has one other delegate type (<code>Behaves_like&lt;T&gt;</code>) and several optional attributes available (<code>Subject, Tag, Ignore, Behavior</code>).&#160; <code>[Subject]</code> provides additional information about the specification. <code>[Tag]</code> is similar to the <code>[Category]</code> attribute in NUnit.&#160; <code>[Ignore]</code> is self-explanatory. <code>[Behavior]</code> marks a class made up entirely of assertions (<code>It</code> delegates).&#160; <code>Behaves_like&lt;T&gt;</code> is a delegate type that can be included in a specification block taking the place of a set of assertions (<code>It</code> delegates).</p>
<p>&#160;</p>
<h4>NUnit – TestFixture-Per-Class </h4>
<p>I have gone from using a TestFixture-Per-Class style to a behavior-driven/context-specification style.&#160; I would like to use the standard HomeController, created in an ASP.NET MVC 1.0 project, as an example class to explore this evolution.&#160; </p>
<p>In my TestFixture-Per-Class days, I may have tested the <code>Index</code> action as follows:</p>
<pre class="brush: csharp;">[TestFixture]
public class HomeControllerTests
{
    [Test]
    public void IndexActionTest()
    {
        var controller = new HomeController();
        var result = (ViewResult) controller.Index();
        Assert.AreEqual(&quot;Welcome to ASP.NET MVC!&quot;, result.ViewData[&quot;Message&quot;]);
    }
}</pre>
<p>I do like the simplicity of the code.&#160; One line to set up the test, one to execute, and one to assert.&#160; There is a little ceremony involved with marking the class and methods with the NUnit attributes.&#160; With this simple test, it is easy to distinguish the setup code from the assertion; yet, a more complex test would make scanning the test more difficult.&#160; Comments can help, but tend to just add noise.</p>
<p>&#160;</p>
<h4>NUnit – Arrange/Act/Assert</h4>
<p>With the advent of BDD, I started naming my classes and expectations as inspired by BDD syntax.&#160; I might have used the <code>[SetUp]</code> attribute or a base class to organize my test code in a style similar to the following:</p>
<pre class="brush: csharp;">[TestFixture]
public class when_I_go_to_the_home_page: AAA
{
    private HomeController _controller;
    private ViewResult _result;

    protected override void Arrange()
    {
        _controller = new HomeController();
    }
    protected override void Act()
    {
        _result = (ViewResult)_controller.Index();
    }

    [Test]
    public void then_the_welcome_message_should_be_displayed()
    {
        _result.ViewData[&quot;Message&quot;].ShouldEqual(&quot;Welcome to ASP.NET MVC!&quot;);
    }
}</pre>
<p>This actively separates out the different responsibilities of the test.&#160; You can see where the setup code is, as well as the action being tested.&#160; The assertion is the only line of code in the test method.&#160; There is still ceremony involved with the attributes.&#160; Plus, we have added a little more ceremony and noise with the <code>Arrange()</code> and <code>Act()</code> overrides.&#160; This simple test does not necessarily need the parts split in this manner, but it would help with more complex scenarios.&#160; Additionally, the assertion is using extension methods based on the NUnit Assert classes which provides a little more clarity to the assertion.</p>
<p>&#160;</p>
<h4>MSpec</h4>
<p>Once started down the path of a behavior-driven (or context/specification) style, I started looking at frameworks devoted to that style.&#160; MSpec is one of those frameworks.&#160; Here is the Index action specification in MSpec:</p>
<pre class="brush: csharp;">public class when_I_go_to_the_home_page
{
    Establish context = () =&gt;  _controller = new HomeController();
    Because of = () =&gt; _result = (ViewResult)_controller.Index();
    It should_display_the_welcome_message = () =&gt; _result.ViewData[&quot;Message&quot;].ShouldEqual(&quot;Welcome to ASP.NET MVC!&quot;); 

    static HomeController _controller;
    static ViewResult _result;
}</pre>
<p>If you look closely, this specification is very similar to the first NUnit test.&#160; However, there are no attributes to specify and the specification has a distinct functional separation.&#160; The Establish/Because/It syntax is analogous to the Given/When/Then language used in user stories or Arrange/Act/Assert syntaxes used in the previous example.&#160; In my opinion, this has less noise than the test using NUnit with an AAA base class – even while using the lambda delegate syntax.</p>
<p>&#160;</p>
<h4>MSpec &#8211; SpecificationFor&lt;ClassUnderTest&gt;</h4>
<p>I often use a base class to handle some of my setup code. Using StructureMap and RhinoMocks, it generates and injects proxied dependencies for the given class.&#160; In this example, I have no dependencies to wire up, but I think you can still see the benefits.</p>
<pre class="brush: csharp;">public class when_I_go_to_the_home_page : SpecificationFor&lt;HomeController&gt;
{
    Because of = () =&gt; _result = (ViewResult)ClassUnderTest.Index();
    It should_display_the_welcome_message = () =&gt; _result.ViewData[&quot;Message&quot;].ShouldEqual(&quot;Welcome to ASP.NET MVC!&quot;); 

    static ViewResult _result;
}</pre>
<p>The Establish delegate is not needed in this specification, because I have wired up the class via the base class.&#160; I feel this version is most clear and concise of all the examples, and neither cryptic nor cumbersome&#160; If you are interested in the <code>SpecificationFor&lt;T&gt;</code> base class and the supporting components, check out my previous <a href="http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/" target="_blank">post</a>.&#160; </p>
<p>&#160;</p>
<h4>Looking to the Future</h4>
<p>I hope that this post has shown that MSpec does not have to be cryptic, nor cumbersome.&#160; If you considered it as such before, please take another critical look.</p>
<p>Given the evolving state of the craft, I am sure that my test/specification style will continue to gradually change.&#160; I am sure that my framework of choice will eventually change as well, especially as each framework is extended and challenged by others.&#160; Hopefully, you can be open to evolving your style as well.</p>
<p><script type="text/javascript">// <![CDATA[
 var cirerolGaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + cirerolGaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
// ]]&gt;</script><script type="text/javascript">// <![CDATA[
 var cirerolPageTracker = _gat._getTracker('UA-8257866-3'); cirerolPageTracker._initData(); cirerolPageTracker._trackPageview();
// ]]&gt;</script></p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/03/01/an-evolution-of-test-specification-styles-my-journey-to-mspec/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Wrapping up the StructureMap Automocking Container</title>
		<link>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/</link>
		<comments>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/#comments</comments>
		<pubDate>Mon, 30 Nov 2009 07:21:43 +0000</pubDate>
		<dc:creator>Richard Cirerol</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[StructureMap; Automocking; MSpec;]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/</guid>
		<description><![CDATA[<p><font color="#804040"><strong>UPDATE</strong>: I apologize…the original wrapper did not allow injected dependencies.&#160; I have fixed this bug and updated the sample.</font></p> I have been using StructureMap.AutoMocking with MSpec (Machine.Specifications) and Rhino.Mocks for a few months now.  Although I am very comfortable with the patterns that emerge from using the frameworks together, introducing StructureMap.Automocking to other developers is sometimes challenging. I decided to wrap the details of the container to make the intention clearer and explanation easier.  I have started using this wrapper in my projects, and have found it makes building up specifications more efficient in my daily coding.]]></description>
			<content:encoded><![CDATA[<p><span style="color: #804040;"><strong>UPDATE</strong>: I apologize…the original wrapper did not allow injected dependencies.  I have fixed this bug and updated the sample.</span></p>
<p>I have been using StructureMap.AutoMocking with MSpec (Machine.Specifications) and Rhino.Mocks for a few months now.  Although I am very comfortable with the patterns that emerge from using the frameworks together, introducing StructureMap.Automocking to other developers is sometimes challenging.</p>
<p>When viewing a specification or test set up with the Rhino.Mocks or Moq automocking container, what is being tested is not readily apparent.  Once the concept is explained and demonstrated, these same developers seem to have no issue with maintaining the specifications/tests.</p>
<p>I decided to wrap the details of the container to make the intention clearer and explanation easier.  I have started using this wrapper in my projects, and have found it makes building up specifications more efficient in my daily coding.</p>
<p>Let me know whether this is useful to you, or how it could be made more useful.</p>
<h4>The Examples</h4>
<p>Let’s contrive an example.  We’ll say we have a coffee machine that grinds its own beans before brewing. However, the hopper has to have beans before starting the grind.  Here is the basic specification:</p>
<table border="1" cellspacing="0" cellpadding="2" width="533">
<tbody>
<tr>
<td width="117" valign="top">Action/Behavior</td>
<td width="414" valign="top">Prepare coffee grounds for 12 cups of coffee</td>
</tr>
<tr>
<td rowspan="2" width="117" valign="top">Expectations</td>
<td width="414" valign="top">Should check that hopper has beans (mock returns true)</td>
</tr>
<tr>
<td width="414" valign="top">Because hopper has beans, should ask grinder to grind enough beans for 12 cups of coffee</td>
</tr>
</tbody>
</table>
<p>We could start without a container, using Rhino.Mocks to build up the CoffeeMachine dependencies manually:</p>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using vanilla Rhino.Mocks")]
public class Example01_when_preparing_coffee_grounds
{
    Establish context = () =&gt;
        {
            Grinder = MockRepository.GenerateMock&lt;IGrinder&gt;();
            Hopper = MockRepository.GenerateMock&lt;IHopper&gt;();
            Hopper.Expect(x =&gt; x.HasBeans()).Return(true);
            CoffeeMachine = new CoffeeMachine(Grinder, Hopper);
        };

    Because of = () =&gt; _coffeeMachine.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static CoffeeMachine CoffeeMachine;
}</pre>
<p>For those of you not familiar with the MSpec style, please refer to the following posts:</p>
<ul>
<li><a href="http://blog.wekeroad.com/blog/make-bdd-your-bff-2/" target="_blank">Make BDD Your BFF</a></li>
<li><a href="http://www.lostechies.com/blogs/seanbiefeld/archive/2009/08/25/step-by-step-to-using-machine-specifications-with-resharper.aspx" target="_blank">Step by Step to Using MSpec (Machine.Specifications) with ReSharper</a></li>
<li><a href="http://elegantcode.com/2009/07/05/mspec-take-2/" target="_blank">MSpec &#8211; Take 2</a></li>
<li><a href="http://marcinobel.com/index.php/mspec-bdd-installer/" target="_blank">MSpec BDD framework installer</a></li>
<li><strong>Updated! </strong>From the <a href="http://blog.cwa.me.uk/2009/11/30/the-morning-brew-487/" target="_blank">Morning Brew #487</a>: BDD with MSpec and Rhino Auto Mocks, parts  <a href="http://telldontask.wordpress.com/2009/11/10/bdd-with-mspec-and-rhino-auto-mocks/" target="_blank">1</a>, <a href="http://telldontask.wordpress.com/2009/11/19/bdd-with-mspec-and-rhino-auto-mocks-part-2/" target="_blank">2</a>, and <a href="http://telldontask.wordpress.com/2009/11/29/bdd-with-mspec-and-rhino-auto-mocks-part-3/" target="_blank">3</a><br />
Here is the same specification using the RhinoAutoMocker&lt;T&gt; class provided by StructureMap.AutoMocking:</li>
</ul>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using RhinoAutoMocker&lt;CoffeeMachine&gt;")]
public class Example02_when_preparing_coffee_grounds
{
    Establish context = () =&gt;
        {
            CoffeeMachine = new RhinoAutoMocker&lt;CoffeeMachine&gt;();
            Grinder = CoffeeMachine.Get&lt;IGrinder&gt;();
            Hopper = CoffeeMachine.Get&lt;IHopper&gt;();
            Hopper.Expect(x =&gt; x.HasBeans()).Return(true);
        };

    Because of = () =&gt; v.ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static RhinoAutoMocker&lt;CoffeeMachine&gt; CoffeeMachine;
}</pre>
<p>Although I think this looks cleaner, the initialization of CoffeeMachine causes some confusion. Unfortunately, a common question would be, “Is RhinoAutoMocker&lt;CoffeeMachine&gt; creating a mocked version of CoffeeMachine?” Well, not exactly.</p>
<p>RhinoAutoMocker is an implementation of the AutoMocker base class which uses StructureMap to fill dependencies.  The RhinoAutoMocker implementation of the container uses Rhino.Mocks to generate all of dependencies of the target class, whereas the MoqAutoMocker implementation uses Moq.  (Optionally, the target class can be partially mocked in order to further isolate behavior.)  We then retrieve the class under test (in this case, CoffeeMachine) and its dependencies (IGrinder and IHopper) from the container for use.</p>
<p>If you do not need to setup any expectations in the specification, there is no need to retrieve the dependency from the container.  However, in this specification, we need both dependencies.</p>
<p><em>(Incidentally, I do not like the ClassUnderTest name.  I may end up changing this to Instance, ClassInstance, TargetClass, or something similar.  Suggestions?)</em></p>
<p>By moving the initialization of the RhinoAutoMocker to a base class, some of the chattiness of the context can be hidden.</p>
<ul>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using RhinoAutoMocker base")]
public class Example03_when_preparing_coffee_grounds : with_rhinoautomocker
{
    Establish context = () =&gt; Hopper.Expect(x =&gt; x.HasBeans()).Return(true);

    Because of = () =&gt; CoffeeMachine.ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

}

[Subject("using RhinoAutoMocker&lt;T&gt;")]
public class with_rhinoautomocker
{
    protected static IGrinder Grinder;
    protected static IHopper Hopper;
    protected static RhinoAutoMocker&lt;CoffeeMachine&gt; CoffeeMachine;

    Establish context = () =&gt;
    {
        CoffeeMachine = new RhinoAutoMocker&lt;CoffeeMachine&gt;();
        Grinder = CoffeeMachine.Get&lt;IGrinder&gt;();
        Hopper = CoffeeMachine.Get&lt;IHopper&gt;();
    };
}</pre>
<p>However, we are still initializing and accessing the class in a less than optimal manner.To make the usage of the container a little more seamless, I decided to create a wrapper and factory for the AutoMocker.  Setup of the dependencies and expectations are done through an AutoMocker wrapper object.  The instance of the class under test is accessed through a ClassUnderTest object.</p>
<h4>The Result</h4>
<p>The specification (and base class) now look like this:</p>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using coffee machine base")]
public class Example05_when_preparing_coffee_grounds : with_coffee_machine
{
    Establish context = () =&gt; Hopper.Expect(x =&gt; x.HasBeans()).Return(true);

    Because of = () =&gt; ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));
}

[Subject("using SpecificationFor&lt;CoffeeMachine&gt;")]
public class with_coffee_machine : SpecificationFor&lt;CoffeeMachine&gt;
{
    protected static IGrinder Grinder;
    protected static IHopper Hopper;

    public with_coffee_machine
    {
        Grinder = AutoMocker.Get&lt;IGrinder&gt;();
        Hopper = AutoMocker.Get&lt;IHopper&gt;();
    }
}</pre>
<p>As you can see, the base class inherits from SpecificationFor&lt;T&gt;.  The default constructor uses Rhino.Mocks(MockMode.AAA) to generate the dependencies.  It then exposes a AutoMocker object, which is just the wrapper around the AutoMocker base class.  It also exposes a ClassUnderTest object.  If I didn’t need to use the dependencies, I could make the <em>Example05_when_preparing_coffee_grounds</em> class inherit from <em>SpecificationFor&lt;CoffeeMachine&gt; </em>instead of inheriting from the base class<em>.</em></p>
<h4>The Code</h4>
<p>I have included the code for the wrapper below for your review.  The code and six examples are available on my <a href="http://codeprogression.googlecode.com/svn/trunk/CodeProgression.Framework.Testing" target="_blank">Google code repository</a>. The repository also includes an example using the MoqAutoMocker.  All the examples have the same assertions, but are built up using the different techniques.</p>
<pre class="brush: csharp;">namespace CodeProgression.Framework.Testing
{
    public abstract class SpecificationFor&lt;T&gt; where T: class
    {
        protected static ClassUnderTest&lt;T&gt; Factory;

        // UPDATE 2009-12-21:
        //   Moved initialization here
        protected static T ClassUnderTest {get {return AutoMocker.Instance;} }

        protected SpecificationFor()
        {
            AutoMocker = AutoMockFactory.CreateTarget&lt;T&gt;();

            // UPDATE 2009-12-21:
            //    Initializing here prevented injected dependencies!
            // AutoMocker.PartialMockTheClassUnderTest();
            // ClassUnderTest = AutoMocker.Instance;
        }

        protected SpecificationFor(AutoMockType type)
        {
            AutoMocker = AutoMockFactory.CreateTarget&lt;T&gt;(type);

            // UPDATE 2009-12-21:
            // Initializing here prevented injected dependencies!
            // AutoMocker.PartialMockTheClassUnderTest();
            // ClassUnderTest = AutoMocker.Instance;
        }
    }

    public static class AutoMockFactory
    {
        public static ClassUnderTest&lt;TARGETCLASS&gt; CreateTarget&lt;TARGETCLASS&gt;() where TARGETCLASS : class
        {
            return CreateTarget&lt;TARGETCLASS&gt;(AutoMockType.RhinoMocksAAA);
        }

        public static ClassUnderTest&lt;TARGETCLASS&gt; CreateTarget&lt;TARGETCLASS&gt;(AutoMockType framework) where TARGETCLASS : class
        {
            AutoMocker&lt;TARGETCLASS&gt; mocker;
            ServiceLocator serviceLocator;
            switch (framework)
            {
                case AutoMockType.RhinoMocksAAA:
                    mocker = new RhinoAutoMocker&lt;TARGETCLASS&gt;(MockMode.AAA);
                    serviceLocator = new RhinoMocksAAAServiceLocator();
                    break;
                case AutoMockType.RhinoMocksClassic:
                    mocker = new RhinoAutoMocker&lt;TARGETCLASS&gt;(MockMode.RecordAndReplay);
                    serviceLocator = new RhinoMocksClassicServiceLocator();
                    break;
                case AutoMockType.Moq:
                    mocker = new MoqAutoMocker&lt;TARGETCLASS&gt;();
                    serviceLocator = new MoqServiceLocator();
                    break;
                default:
                    throw new ArgumentOutOfRangeException("framework");
            }
            return new ClassUnderTest&lt;TARGETCLASS&gt;(mocker, serviceLocator);
        }
    }

    public enum AutoMockType
    {
        Moq,
        RhinoMocksAAA,
        RhinoMocksClassic
    }

    public class ClassUnderTest&lt;TARGETCLASS&gt; where TARGETCLASS : class
    {
        readonly IAutoMocker&lt;TARGETCLASS&gt; _mocker;
        readonly ServiceLocator _serviceLocator;

        public ClassUnderTest(IAutoMocker&lt;TARGETCLASS&gt; mocker, ServiceLocator serviceLocator)
        {
            _mocker = mocker;
            _serviceLocator = serviceLocator;
        }

        public AutoMockedContainer Container
        {
            get { return _mocker.Container; }
        }

        public TARGETCLASS Instance
        {
            get { return _mocker.ClassUnderTest; }
        }

        public void MockObjectFactory()
        {
            _mocker.MockObjectFactory();
        }

        public void PartialMockTheClassUnderTest()
        {
            _mocker.PartialMockTheClassUnderTest();
        }

        public T Get&lt;T&gt;() where T : class
        {
            return _mocker.Get&lt;T&gt;();
        }

        public void Inject(Type pluginType, object stub)
        {
            _mocker.Inject(pluginType, stub);
        }

        public void Inject&lt;T&gt;(T target)
        {
            _mocker.Inject(target);
        }

        public T AddAdditionalMockFor&lt;T&gt;() where T : class
        {
            return _mocker.AddAdditionalMockFor&lt;T&gt;();
        }

        public void UseConcreteClassFor&lt;T&gt;()
        {
            _mocker.UseConcreteClassFor&lt;T&gt;();
        }

        public T[] CreateMockArrayFor&lt;T&gt;(int count) where T : class
        {
            return _mocker.CreateMockArrayFor&lt;T&gt;(count);
        }

        public void InjectArray&lt;T&gt;(T[] stubs)
        {
            _mocker.InjectArray(stubs);
        }

        public T Mock&lt;T&gt;() where T : class
        {
            return _serviceLocator.Service&lt;T&gt;();
        }
        public object Mock(Type serviceType)
        {
            return _serviceLocator.Service(serviceType);
        }
        public T PartialMock&lt;T&gt;() where T : class
        {
            return _serviceLocator.PartialMock&lt;T&gt;();
        }
    }
}</pre>
</ul>
<p><script type="text/javascript">// <![CDATA[
 var cirerolGaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + cirerolGaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
// ]]&gt;</script></p>
<p><script type="text/javascript">// <![CDATA[
 var cirerolPageTracker = _gat._getTracker('UA-8257866-3'); cirerolPageTracker._initData(); cirerolPageTracker._trackPageview();
// ]]&gt;</script></p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>State Pattern, Enumeration Class and Fluent NHibernate (Oh my!)</title>
		<link>http://elegantcode.com/2009/11/01/state-pattern-enumeration-class-and-fluent-nhibernate-oh-my/</link>
		<comments>http://elegantcode.com/2009/11/01/state-pattern-enumeration-class-and-fluent-nhibernate-oh-my/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 04:20:10 +0000</pubDate>
		<dc:creator>Richard Cirerol</dc:creator>
				<category><![CDATA[.Net 3.5]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Fluent NHibernate;State Pattern;Enumeration]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/01/state-pattern-enumeration-class-and-fluent-nhibernate-oh-my/</guid>
		<description><![CDATA[Recently, I needed to change a basic enumeration into a full-fledged state pattern. After getting all my domain classes updated, I began reviewing the persistence layer. And I hit a wall.  I wasn’t sure how I wanted to update my Fluent NHibernate convention to persist the current state.]]></description>
			<content:encoded><![CDATA[<p>Recently, I needed to change a basic enumeration into a full-fledged state pattern. After getting all my domain classes updated, I began reviewing the persistence layer. And I hit a wall.  I wasn’t sure how I wanted to update my Fluent NHibernate convention to persist the current state.</p>
<p>My original classes were similar to this:</p>
<pre class="brush: csharp;">public class MyProgress{
   public virtual Guid Id { get; set; }
   ...
   ...
   public virtual MyStatus Status { get; private set; }
}

public enum MyStatus{
   New,
   InProgress,
   Completed,
   Canceled,
   Failed
}
</pre>
<p>My new state pattern was similar to this:</p>
<pre class="brush: csharp;">
public abstract class MyStatus
{
    public static readonly MyStatus New = new NewStatus();
    public static readonly MyStatus InProgress = new InProgressStatus();
    ...
}

public class NewStatus: MyStatus
{
    public override void Start(MyProgress progress)
    {
        progress.SetStatus(InProgress);
    }
    public override void Cancel(MyProgress progress)
    {
        progress.SetStatus(Cancelled);
    }
    public override void Fail(MyProgress progress)
    {
            progress.SetStatus(Failed);
    }
}
...
</pre>
<p>Here is the problem… My enumeration was persisted as an integer field on the record. Now that I had a state pattern, how should I save my state? I googled the problem and found <a href="http://www.lostechies.com/blogs/derickbailey/archive/2008/11/26/mapping-a-state-pattern-with-nhibernate.aspx" target="_blank">Derick Bailey’s article</a> on the state pattern and Fluent NHibernate. Derick’s pattern works well, but I felt that creating a lookup table in my database just so I can persist a value in another table was not the path I wanted to traverse – I wasn’t persisting an entity, I was persisting a state value on an entity. Not finding any more love from Google, I asked around and was advised to contact fellow Elegant Coder and <a href="http://guild3.com" target="_blank">Guild3</a> member, <a href="http://elegantcode.com/author/jgrundy/" target="_blank">Jason Grundy</a>. Here is Jason’s advice:</p>
<blockquote><p>&#8220;I&#8217;ve recently changed from using Enums to an approach outlined by Jimmy Bogard <a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/08/12/enumeration-classes.aspx">here</a>.  In the Entity I would do something like this:</p>
<pre class="brush: csharp;">
protected int _orderStatusId;
public virtual OrderStatus OrderStatus
{
    get { return Enumeration.FromValue&lt;OrderStatus&gt;(_orderStatusId); }
    set { _orderStatusId = value.Value; }
}
</pre>
<p>Then in Fluent NH you can simply map to the protected member.&#8221;</p></blockquote>
<p>I decided to pursue Jason’s advice.  The result is my database tables did not need to change at all. Here is some snippets of the updated classes:</p>
<pre class="brush: csharp;">
public class MyProgress
{
     public virtual Guid Id {get;set;}
     ...
     protected int _status;
     public virtual MyStatus
     {
         get{ return Enumeration.FromValue&lt;MyStatus&gt;(_status); }
         set{ _status = value.Value; }
     }
     ...
}

public class MyStatus : Enumeration
{
     public static MyStatus New = new NewStatus();
     ...

     private class NewStatus : MyStatus
    {
         public NewStatus() : base (0,"New"){}

         public override void Start(MyProgress progress)
         {
             progress.SetStatus(InProgress);
         }
    }
     ...
</pre>
<p>Notice that the MyStatus class is no longer abstract.  However, the subclasses are all private nested classes, each with a value and a display name.  I set each subclass value to match the enumeration value it replaced.  I did not need to convert my existing data to a new schema.</p>
<p>And here is the Fluent NHibernate override:</p>
<pre class="brush: csharp;">
public class MyProgressOverride : IAutoMappingOverride&lt;MyProgress&gt;
{
    public void Override(AutoMapping&lt;MyProgress&gt; mapping)
    {
        mapping.Map(x =&gt; x.Status)
            .CustomType(typeof(int))
            .Access.CamelCaseField(Prefix.Underscore);
    }
}
</pre>
<p>As you can see, we use convention-based automapping with overrides, but this same map could be used in a standard class map.</p>
<p>Thanks to Jimmy, Derick, and Jason for the inspiration and assistance!</p>
<p><script type="text/javascript"> 
var cirerolGaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + cirerolGaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script><br />
<script type="text/javascript"> 
var cirerolPageTracker = _gat._getTracker('UA-8257866-3');
cirerolPageTracker._initData();
cirerolPageTracker._trackPageview();
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/01/state-pattern-enumeration-class-and-fluent-nhibernate-oh-my/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>AutoMapper Introduction and Samples from NETDUG</title>
		<link>http://elegantcode.com/2009/10/06/automapper-introduction-and-samples-from-netdug/</link>
		<comments>http://elegantcode.com/2009/10/06/automapper-introduction-and-samples-from-netdug/#comments</comments>
		<pubDate>Wed, 07 Oct 2009 05:08:11 +0000</pubDate>
		<dc:creator>Richard Cirerol</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/10/06/automapper-introduction-and-samples-from-netdug/</guid>
		<description><![CDATA[In September, Cory Isakson and I presented AutoMapper to the Boise .NET Developer User Group (NETDUG).&#160; As promised, I have included the sample code here.&#160; AutoMapper 1.0 RC1 is available on the CodePlex site. 
At my company, we have embraced convention-over-configuration throughout our applications, from our data access framework (Fluent NHibernate) to our IoC container [...]]]></description>
			<content:encoded><![CDATA[<p><em>In September, Cory Isakson and I presented AutoMapper to the Boise .NET Developer User Group (NETDUG).&#160; As promised, I have included the sample code </em><a href="http://code.google.com/p/codeprogression/source/browse/sample-projects" target="_blank"><em><strong>here</strong></em></a><em>.&#160; AutoMapper 1.0 RC1 is available on the <a href="automapper.codeplex.com" target="_blank">CodePlex</a> site. </em></p>
<p>At my company, we have embraced convention-over-configuration throughout our applications, from our data access framework (Fluent NHibernate) to our IoC container (StructureMap) to our build scripts to our…well, you get the picture.&#160; However, we had been hitting a pain point in our application when trying to serialize our domain objects for transport across the WCF service layer.&#160; We were also seeing some issues with using domain objects directly in our MVC views. The old way would have been to write that boring left-hand/right-hand code.&#160; We all know that left-hand/right-hand code is ugly and pollutes the methods that should be doing real work with ceremonious busy work.&#160; </p>
<p>Well, just as we were really getting stung by these pain points, Cory and I started talking about AutoMapper.&#160; Now, for those who have no idea what AutoMapper is, check out the <a href="http://automapper.codeplex.com/Wiki/View.aspx?title=Getting%20Started" target="_blank">Getting Started</a> page on <a href="http://automapper.codeplex.com/" target="_blank">CodePlex</a>.&#160; If you want to check out the source, go to the <a href="http://code.google.com/p/automapperhome/" target="_blank">Google code</a> site.&#160; Jimmy Bogard, the AutoMapper author, describes the AutoMapper as a convention-based object-to-object mapper.</p>
<p>&#160;</p>
<h2>Different Means to an End</h2>
<p>&#160;</p>
<p>Here is the basic idea… In the past, I would write this classic chunk of code:</p>
<pre class="brush: csharp;">var meeting = _repository.GetMeetingById(meetingId);
var dto = new MeetingDto();
dto.Begins = meeting.Begins;
dto.End = meeting.End;
dto.Attendees = meeting.Attendees;
dto.AttendeesCount = meeting.Attendees.Count;
//do something meaningful</pre>
<p>With AutoMapper, I can write this instead:</p>
<pre class="brush: csharp;">var meeting = _repository.GetMeetingById(meetingId);
var dto = Mapper.Map&lt;Meeting, MeetingDto&gt;(meeting);
//do something meaningful</pre>
<p>&#160;</p>
<p>Herein lies the beauty of AutoMapper.&#160; When your classes align themselves <em>conventionally</em>, your mapping configuration can be as simple as: </p>
<pre class="brush: csharp;">CreateMap&lt;Meeting,MeetingDto&gt;();</pre>
<p>This is a trivial example, but where AutoMapper shines is in the ability to map lists and nested properties by convention. Or constructing an object based on another object’s properties.&#160; All without littering a method with ceremonial code.</p>
<p>Using an object-to-object mapper does have its drawbacks:</p>
<ol>
<li>The classic left-hand/right-hand code performs faster than mapped code, although Jimmy has made great strides in increasing performance. </li>
<li>When defining unconventional mappings, you will still have left-hand/right-hand code </li>
<li>There will be a learning curve for you (and/or your team) if you have not had experience with convention-based frameworks or some of the .NET 3.5 features. </li>
</ol>
<p><em><strong>However, we have found these drawbacks to be <u>trivial</u> when compared to the benefits.</strong></em></p>
<p>&#160;</p>
<h2>Mapping Toolset</h2>
<p>In addition to providing the convention mappings, Jimmy has provided a toolset for enhancing the mappings. Listed here are several tools we either use or find compelling. </p>
<p><strong>Custom Converters</strong>: Code to convert from source type to destination type. Defined once and implicitly used for all mappings.&#160; </p>
<p><strong>Custom Resolvers</strong>: Code to convert from source value to destination value.&#160; Defined once for use by any mapping, but must be explicitly used by a mapping. </p>
<p><strong>Custom Formatters</strong>: Code to reformat a type for presentation.&#160; Like resolvers, formatters are defined once and explicitly used. </p>
<p><strong>Before/After Map Functions</strong>: Provides the ability to run custom code before or after the mappings are performed. </p>
<p><strong>Validation Assertion</strong>: Provides a method to short-circuit at runtime (or in tests) with an explanatory exception when a mapping may cause failures.&#160; </p>
<p><strong>Mapping Profiles</strong>: Profile is a base class that helps you organize your code.&#160; If you are familiar with StructureMap’s Registry class, you will feel right at home with the Profile class.</p>
<p>&#160;</p>
<h2>Where We Use AutoMapper</h2>
<p>&#160;</p>
<p>We use AutoMapper to transform our object model to our presentation model.&#160; This happens in two places – in our MVC controllers and at our WCF service layer.</p>
<p>In the controllers, we will map from a domain model or DTO into the view model.&#160; We will also map from our view model into a message object for use by the service or domain.</p>
<p>At the service layer, we flatten our domain model into a DTO or map a message object to run a command against the domain.</p>
<p>&#160;</p>
<h2>Code Samples</h2>
<p>&#160;</p>
<p>I am including the sample code used at the NETDUG meeting.&#160; The <a href="http://code.google.com/p/codeprogression/source/browse/sample-projects/NETDUGSample1.zip" target="_blank">first sample</a> shows different ways to setup mappings (inline vs. profiles).&#160; The <a href="http://code.google.com/p/codeprogression/source/browse/sample-projects/NETDUGSample2.zip" target="_blank">second sample</a> shows some usages of custom resolvers, formatters, and before-maps.</p>
<p>Download the AutoMapper source.&#160; Jimmy has provided many sample classes and unit tests showing off the usage of different conventions.&#160; </p>
<p>Matt Hinze also <a href="http://mhinze.com/automapper-in-nerddinner/" target="_blank">posted</a> a sample solution using AutoMapper with NerdDinner (of which I borrowed some custom formatter code – Thanks Matt!). </p>
<p>Download the <a href="http://code.google.com/p/codecampserver/" target="_blank">CodeCampServer source</a>.&#160; It is full of examples and conventions, including using an IoC/DI implementation of the AutoMapper engine.</p>
<p><script type="text/javascript"> 
var cirerolGaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + cirerolGaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script><br />
<script type="text/javascript"> 
var cirerolPageTracker = _gat._getTracker('UA-8257866-3');
cirerolPageTracker._initData();
cirerolPageTracker._trackPageview();
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/10/06/automapper-introduction-and-samples-from-netdug/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Implementing Team City for .NET Projects, Part 5: Deployments</title>
		<link>http://elegantcode.com/2009/08/09/implementing-team-city-for-net-projects-part-5-deployments/</link>
		<comments>http://elegantcode.com/2009/08/09/implementing-team-city-for-net-projects-part-5-deployments/#comments</comments>
		<pubDate>Mon, 10 Aug 2009 05:10:18 +0000</pubDate>
		<dc:creator>Richard Cirerol</dc:creator>
				<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[TeamCity]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/08/09/implementing-team-city-for-net-projects-part-5-deployments/</guid>
		<description><![CDATA[My apologies to all those who have been waiting for the deployment scenario – I appreciate your patience.&#160; My approach to deployments has been a moving target – as it is starting to firm up a bit, I thought&#160; I would write down some thoughts.
For more information on this series, please see the introductory post. [...]]]></description>
			<content:encoded><![CDATA[<p>My apologies to all those who have been waiting for the deployment scenario – I appreciate your patience.&#160; My approach to deployments has been a moving target – as it is starting to firm up a bit, I thought&#160; I would write down some thoughts.</p>
<p><em>For more information on this series, please see the </em><a title="Implementing TeamCity introduction" href="http://elegantcode.com/2009/05/04/implementing-teamcity-for-net-projects-evolving-your-build-automation-solution/" target="_blank">introductory post</a><em></em><em>.</em> In the <a href="http://elegantcode.com/2009/05/24/implementing-teamcity-for-net-projects-part-4-using-build-scripts/" target="_blank">previous post</a>, I discussed build scripts as a way of extending the functionality of TeamCity.&#160; If you downloaded the sample solution, you could see the tasks and structure of the NAnt and Rake scripts.&#160; Since then, I have fully embraced Rake as my default build script engine; therefore, my script examples in this post are Rake scripts.</p>
<blockquote><p>Don’t forget to listen to <a href="http://elegantcode.com/2009/07/23/code-cast-28-jim-wierich/" target="_blank">Elegant Code Cast #28</a> , where Chris Brandsma and I had the privilege of speaking with Jim Wierich, the father of Rake.</p>
</blockquote>
<p>I have modeled the Rake scripts after the Fluent NHibernate and FubuMVC scripts.&#160; I am also very interested in rake-dotnet from Pete Mounce.&#160; Once rake-dotnet has support for NUnit and MSpec, I will be migrating my scripts to use it as a base library.&#160; (Pete, I am actually planning on a patch for both – you know…in my spare time.)&#160; Rake-dotnet is definitely worth checking out, especially if you use xUnit as your test library.</p>
<h4>The Deployment Process</h4>
<p>Here is a representation of my preferred folder structure for a solution:</p>
<p><a href="http://elegantcode.com/wp-content/uploads/2009/08/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="before build" border="0" alt="before build" src="http://elegantcode.com/wp-content/uploads/2009/08/image_thumb.png" width="160" height="232" /></a> </p>
<p>The following tasks are completed on each check-in:</p>
<ul>
<li>MSBuild is called to clean and build both debug and release versions of the projects in the solution </li>
<li>Tests are run </li>
<li>An archive is created of each site and/or binaries (both debug and release versions), build scripts, and possibly SQL scripts </li>
</ul>
<p>A post-build event is run on each web application project to pre-compile the site into a specific directory for each compilation type. My post build event looks like this:</p>
<blockquote><p>%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_compiler.exe&#160; <br />–nologo -errorstack -f -u -c -p $(ProjectDir) -v temp       <br />$(SolutionDir)\Build\results\PrecompiledWeb\$(ConfigurationName)\$(TargetName)</p>
</blockquote>
<p>The post-build event is also a good place to add any plug-in type binaries not directly depended on by your site, but included in your solution. Each site also has a set of configuration sources for each environment up the chain (nightly, test, staging, production)</p>
<p>After the build, I have added several folders and archive files to the build directory:</p>
<p><a href="http://elegantcode.com/wp-content/uploads/2009/08/image1.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="after build" border="0" alt="after build" src="http://elegantcode.com/wp-content/uploads/2009/08/image_thumb1.png" width="167" height="231" /></a>&#160;</p>
<p>The archive files are stored in subsequent builds.&#160; I never have to rebuild my solution for each platform.&#160; Here is an example artifact path definition:</p>
<p><a href="http://elegantcode.com/wp-content/uploads/2009/08/image2.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2009/08/image_thumb2.png" width="244" height="74" /></a> </p>
<p>For the nightly build artifacts, I have the following definitions:</p>
<blockquote><p>build/*=&gt;Build      <br />build/results/Debug.zip=&gt;Sites       <br />build/results/Release.zip=&gt;Sites       <br />build/results/DebugBinaries.zip=&gt;Binaries       <br />build/results/ReleaseBinaries.zip=&gt;Binaries</p>
</blockquote>
<p>For subsequent builds, the definitions change slightly:</p>
<blockquote><p>build/**/*=&gt;build     <br />sites/**/*=&gt;sites      <br />binaries/**/*=&gt;binaries</p>
</blockquote>
<p>When the nightly build is run:</p>
<ul>
<li>
<div style="margin-right: 0px">The check-in build is run, if it has pending changes</div>
</li>
<li>
<div style="margin-right: 0px">The desired (debug or release) site is unzipped and pushed to the nightly build site</div>
</li>
<li>
<div style="margin-right: 0px">The configuration files for the site are overwritten with the nightly build environment files <em>(See script below) You may update the configuration files before or after pushing your site, depending on your preference)</em></div>
</li>
<li>
<div style="margin-right: 0px">Artifacts of the sites, binaries, and build scripts are stored with the build on TeamCity</div>
</li>
<li>
<div style="margin-right: 0px">Smoke test the sites (see script below)</div>
</li>
</ul>
<ul>When a subsequent environment is run:
<li>
<div style="margin-right: 0px">Clean all files before build (checkmark on the VCS configuration page for the build)</div>
</li>
<li>
<div style="margin-right: 0px">The artifacts from the dependent build are retrieved (configured from the dependencies page of the build configuration).       <br /><a href="http://elegantcode.com/wp-content/uploads/2009/08/image3.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2009/08/image_thumb3.png" width="244" height="154" /></a> </div>
</li>
<li>
<div style="margin-right: 0px">The build tools are retrieved from source control using an edit checkout rule (+:lib)       <br /><em>Whereas the compile-check and nightly build configurations get the entire folder structure from version control, the subsequent builds only retrieve the <strong>lib</strong> directory.<a href="http://elegantcode.com/wp-content/uploads/2009/08/image4.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; margin-left: 0px; border-top: 0px; margin-right: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2009/08/image_thumb4.png" width="244" height="135" /></a></em></div>
</li>
<li>
<div style="margin-right: 0px">The existing site is archived</div>
</li>
<li>
<div style="margin-right: 0px">The new site is unzipped and pushed</div>
</li>
<li>
<div style="margin-right: 0px">The configuration files for the site are overwritten with the specific environment files</div>
</li>
<li>
<div style="margin-right: 0px">Artifacts of the sites, binaries, and build scripts are stored with the build on TeamCity</div>
</li>
<li>
<div style="margin-right: 0px">Smoke test the sites</div>
</li>
</ul>
<ul>The idea is to feed up the chain of deployments the artifacts needed to complete the next deployment.&#160; It takes a little trial and error to get it right, but the benefits are worth it.&#160; Our current builds at <a href="http://www.unitymg.com" target="_blank">Unity Media Group</a> take 2 to 3 minutes for the compile check (including test runs and zipping files), then approximately 45 seconds to deploy the site on the internal network.</ul>
<p style="margin-right: 0px">What I have not automated yet (but would like to):</p>
<ul>
<li>
<div style="margin-right: 0px">Reconfiguring the sites to point to a maintenance page while deploying</div>
</li>
<li>
<div style="margin-right: 0px">Running the SQL schema compare and integration<em> </em>or run update scripts         <br /><em>&#8211; I have run compare/integration scripts previously, but they tended to be more hassle than running them manually.&#160; Still looking for better ways to do this, though.</em></div>
</li>
<li>
<div style="margin-right: 0px">If building binaries for use by other projects, update those projects with the new binaries</div>
</li>
<li>
<div style="margin-right: 0px">Run data scrubbing scripts (for creating known default environments for test or demonstration sites)</div>
</li>
</ul>
<ul>
<h4>
<ul>Rake File Snippets</ul>
</h4>
<p> To update the configuration files, I define the following method in my helper file:</ul>
<pre class="brush: ruby;"> # UPDATING CONFIGURATION FILES  def copyToDirectory(zip_file, website_dir, config_type)  throw(&quot;ZipFile does not exist!&quot;, zip_file) unless File.exist?(zip_file)  seven_zip = SevenZip.new :ziparchive =&gt;  zip_file, :directory=&gt;website_dir  seven_zip.unzip

  # WEB_PROJECTS: list of web application projects with a Config directory  #     =&gt; WEB_PROJECTS = ['ElegantCode.Example.Administration',     #                            'ElegantCode.Example.Client',   #                            'ElegantCode.Example.Services']  WEB_PROJECTS.each do |site|  puts &quot;##teamcity[progressMessage 'Updating application settings for #{site}']&quot;    list=FileList.new(&quot;#{website_dir}/#{site}/Config/*-#{config_type}.config&quot;)    list.each do |file|      target = file.gsub(&quot;-#{config_type}&quot;,'')      puts &quot;##teamcity[progressMessage 'Copying #{file.to_s} to #{target.to_s}']&quot;      cp file,target    end  endend</pre>
</p>
</p>
</p>
</p>
<p>And this is how I use it in the rakefile:</p>
<pre class="brush: ruby;"># USAGE:zip_file = File.expand_path(File.join(&quot;..&quot;,&quot;Sites&quot;, 'Debug.zip'))website_dir = File.join('Z:', 'AdventureMVC')copyToDirectory zip_file, website_dir, 'sandbox'</pre>
<p>Similarly, to smoke test the site, I have the following class in my helper file:</p>
<pre class="brush: ruby;"># SMOKE TEST class PreJIT    attr_reader :sites

    def self.compile(sites)        sites.each do |site|            puts &quot;##teamcity[progressMessage 'Pre-jitting #{site}']&quot;            open (site)        end    endend</pre>
<p>And this is how I use it:</p>
<pre class="brush: ruby;"># USAGE:sites = ['http://test.example.com/admin', 'http://test.example.com']PreJIT.compile(sites)</pre>
<p>If the site&#160; has a 40x/50x error, the build will fail.</p>
<p>There is much more to the rake scripts; however, you should peruse the rake files from Fluent NHibernate or FubuMVC for more ideas on writing your own Rake scripts.&#160; You can incorporate rake-dotnet into your rake environment, as well.&#160; Finally, you can accomplish the same tasks using MSBuild or NAnt, if you feel more confident in those environments.</p>
<p>Until next time..</p>
<p><a title="Fluent NHibernate on googlecode" href="http://code.google.com/p/fluent-nhibernate/" target="_blank">Fluent NHibernate</a></p>
<p><a title="FubuMVC on googlecode" href="http://code.google.com/p/fubumvc/" target="_blank">FubuMVC</a></p>
<p><a title="rake-dotnet on GitHub" href="http://github.com/petemounce/rake-dotnet/tree/master" target="_blank">rake-dotnet</a></p>
<p><a href="http://www.jetbrains.com/teamcity" target="_blank">TeamCity</a></p>
<p><a href="http://rake.rubyforge.org/" target="_blank">Rake</a></p>
<p><script type="text/javascript"> 
var cirerolGaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + cirerolGaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script><br />
<script type="text/javascript"> 
var cirerolPageTracker = _gat._getTracker('UA-8257866-3');
cirerolPageTracker._initData();
cirerolPageTracker._trackPageview();
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/08/09/implementing-team-city-for-net-projects-part-5-deployments/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Implementing TeamCity for .NET Projects, Part 4: Using Build Scripts</title>
		<link>http://elegantcode.com/2009/05/24/implementing-teamcity-for-net-projects-part-4-using-build-scripts/</link>
		<comments>http://elegantcode.com/2009/05/24/implementing-teamcity-for-net-projects-part-4-using-build-scripts/#comments</comments>
		<pubDate>Mon, 25 May 2009 03:54:57 +0000</pubDate>
		<dc:creator>Richard Cirerol</dc:creator>
				<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[NAnt]]></category>
		<category><![CDATA[Rake]]></category>
		<category><![CDATA[TeamCity]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/05/24/implementing-teamcity-for-net-projects-part-4-using-build-scripts/</guid>
		<description><![CDATA[For more information on this series, please see the introductory post.  This post also assumes that you have completed parts 1-3.  The sample solution has been updated with new build scripts as of May 24, 2009.  If you have downloaded the solution previously, please download the updated solution.  You can explore the source or create [...]]]></description>
			<content:encoded><![CDATA[<p><em>For more information on this series, please see the </em><a title="Implementing TeamCity introduction" href="http://elegantcode.com/2009/05/04/implementing-teamcity-for-net-projects-evolving-your-build-automation-solution/" target="_blank">introductory post</a><em></em><em>.  This post also assumes that you have completed parts <a title="Just Build It!" href="http://codeprogression.blogspot.com/2009/04/implementing-teamcity-for-net-projects.html" target="_blank">1</a>-3.  The sample solution has been updated with new build scripts as of May 24, 2009.  If you have downloaded the solution previously, please download the updated solution.  You can explore the source or create a working copy.  A zip file has been provided for you to download to import into your own writeable repository.</em></p>
<p>For more advanced or complex build scenarios, the build it solution runners prove somewhat inflexible.  Once you have arrived at this conclusion, you will most likely start investigating some of the other build runner options.</p>
<p>For .NET projects, the two obvious choices are MSBuild and NAnt.  The new hotness for building .NET projects is Rake.  And, if you use a scripting language not built into TeamCity (such as FinalBuilder, Psake, or shell scripts), the command line runner is your friend.  TeamCity also has two .NET build runners specifically targeting code inspection: Duplicates finder and FxCop.</p>
<p>I have been using NAnt for several years to build both web and desktop applications.  NAnt has been fairly quiet for the last couple years.  The latest official release (0.86 Beta 1) is dated December 2007, but there has been sporadic 0.86 Beta 2 activity in the nightly releases.</p>
<p>I have just started working with Rake for build scripts. (A big thanks to the <a href="http://fluentnhibernate.org/" target="_blank">Fluent NHibernate</a> and <a href="http://fubumvc.pbworks.com/" target="_blank">FubuMVC</a> contributors for their pioneering efforts on this front.)  Rake, like Ruby itself, seems to be infinitely extensible.</p>
<h4>What Should a Build Script Do?</h4>
<p>My build scripts need to at least handle the following targets/tasks:</p>
<ol>
<li>Compile the application</li>
<li>Run the tests</li>
<li>Provide a code coverage report</li>
<li>Zip up the compiled application for artifact retention</li>
<li>Update the configuration files</li>
<li>Publish the website to a folder or IIS virtual directory</li>
</ol>
<ul>TeamCity natively handles 1 and 2, but we will be duplicating that functionality with the build scripts.  TeamCity also allows you to download your artifacts as a zip file, but does not store it as one.  TeamCity does not provide code coverage for .NET projects.  However, it does for Java projects.)</ul>
<ul>Our NAnt and Rake scripts will handle the all the tasks.  I will cover the first four tasks in this post.  I will cover the other three in another post. </ul>
<h4>Setting Up an NAnt Build Runner</h4>
<p>We’ll start with an NAnt Build Runner.  In your TeamCity website:</p>
<ul>
<li>From the Projects page, click the drop arrow next to the existing project and click on Edit Settings</li>
<li>On the right hand side of the screen, click on the Copy button to copy the configuration</li>
<li>Name the new build configuration “Just Build It! (with NAnt)”</li>
<li>Select the Runner link from the navigation bar on the right</li>
</ul>
<p>Based on the sample solution, enter the following values and save your changes.  Leave all other values at their defaults. (If your solution is structured differently, adjust accordingly.)</p>
<table border="1" cellspacing="0" cellpadding="2" width="400">
<tbody>
<tr>
<td width="200" valign="top"><strong>Build Runner:</strong></td>
<td width="200" valign="top">NAnt</td>
</tr>
<tr>
<td width="200" valign="top"><strong>Path to a build file:</strong></td>
<td width="200" valign="top">nant.build</td>
</tr>
<tr>
<td width="200" valign="top"><strong>NAnt Home:</strong></td>
<td width="200" valign="top">lib/nant</td>
</tr>
</tbody>
</table>
<p>Leaving the Targets text box blank will force the runner to use the default target.</p>
<blockquote><p>The default targets in thee script files create a zipped file of the website and code coverage results from the free NCover Community edition.  I am using a couple custom tasks from <a href="http://www.kiwidude.com/blog/" target="_blank">kiwidude</a> for integrating NCover with the NAnt script. </p>
<p>In the General Settings page, add the following to the Artifacts text box to force both files to show up as artifacts:</p>
<pre class="brush: plain; gutter: false;">results/Artifacts.zip
results/CoverageReport.html=&gt;ncover</pre>
<p> <br />
Creating custom tabs is fairly simple as well.  Add the following entry to the <strong><em>&lt;TeamCity data directory&gt;/config/main-config.xml</em></strong> (the default data directory is named <em><strong>.BuildServer </strong>to create a tab that shows the NCover results for each build</em>:</p>
<pre class="brush: xml; gutter: false;	">&lt;report-tab title="NCover"
basePath="ncover"
startPage="CoverageReport.html" /&gt;</pre>
<p>(Thanks to Laurent Kempé for the <a href="http://weblogs.asp.net/lkempe/archive/2008/03/30/integration-of-ncover-into-team-city-for-tech-head-brothers.aspx" target="_blank">instructions</a> on integrating NCover with TeamCity)</p></blockquote>
<h4>Setting Up a Rake Build Runner</h4>
<p>Make another copy of a configuration and name the new build configuration “Just Build It! (with Rake)”. This time select Rake as the build runner on the Build Runner page.  Leave all other values at their default.  (The Rakefile in the root directory will be used.  I modified the rake scripts from the FubuMVC project for this solution.)</p>
<p>You will need Ruby and a couple of Gems to get started.  Check the information in the Ruby_Not_Installed.txt file in the root directory of the sample solution. </p>
<h4>Setting Up an MSBuild Build Runner</h4>
<p>I actually do not have an example of an MSBuild script (because I do not have enough experience with MSBuild).  Setting up the build runner is similar to the NAnt and Rake runners.  If you are interested in this build runner type, check out <a href="http://www.buzzuti.com/post/TeamCity-1-Creating-an-MSBuild-File-and-talks-on-Continuous-Integration.aspx" target="_blank">Ryan Anderson’s posts</a>. He has done an excellent job detailing the process.</p>
<hr /> <strong>Upcoming posts:</strong></p>
<ul>
<li>Deployment: Using TeamCity and build scripts to update different deployment environments.</li>
<li>Setting up notifications: We will look at the different options for notifications, such as email and the tray notifier.</li>
</ul>
<hr />
<a href="http://www.jetbrains.com/teamcity" target="_blank">JetBrains TeamCity</a><br />
<a href="http://codeprogression.googlecode.com" target="_blank">Sample Project on GoogleCode</a><br />
<a href="http://nant.sourceforge.net" target="_blank">NAnt</a> / <a href="http://nantcontrib.sourceforge.net/" target="_blank">NAntContrib</a><br />
<a href="http://www.kiwidude.com/dotnet/DownloadPage.html" target="_blank">NCoverExplorer Downloads</a><br />
<a href="http://nant.sourceforge.net" target="_blank">NAnt</a><br />
<a href="http://nantcontrib.sourceforge.net/" target="_blank">NAntContrib</a><br />
<a href="http://www.kiwidude.com/dotnet/DownloadPage.html" target="_blank">NCoverExplorer Download Page (with NAnt/MSBuild documentation links)</a><br />
<a href="http://www.ruby-lang.org/en/downloads/" target="_blank">Ruby Downloads</a></p>
<p><script type="text/javascript"> 
var cirerolGaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + cirerolGaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script><br />
<script type="text/javascript"> 
var cirerolPageTracker = _gat._getTracker('UA-8257866-3');
cirerolPageTracker._initData();
cirerolPageTracker._trackPageview();
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/05/24/implementing-teamcity-for-net-projects-part-4-using-build-scripts/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Are you ready for Portland Code Camp?</title>
		<link>http://elegantcode.com/2009/05/24/are-you-ready-for-portland-code-camp/</link>
		<comments>http://elegantcode.com/2009/05/24/are-you-ready-for-portland-code-camp/#comments</comments>
		<pubDate>Sun, 24 May 2009 21:05:14 +0000</pubDate>
		<dc:creator>Richard Cirerol</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[Portland Code Camp]]></category>

		<guid isPermaLink="false">http://elegantcode.com/?p=2408</guid>
		<description><![CDATA[Portland Code Camp is next Saturday.  Over 60 sessions have been submitted so far from members of the community, and several of the Elegant Coders have submitted presentations.  We would love to have you show up; so if you are able, please register and attend.  When you register, please RSVP and vote for your favorite [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://portlandcodecamp.org">Portland Code Camp</a> is next Saturday.  Over 60 sessions have been submitted so far from members of the community, and several of the Elegant Coders have submitted presentations.  We would love to have you show up; so if you are able, please register and attend.  When you register, please RSVP and vote for your favorite sessions.  You can even submit your own presentation until midnight tonight!!</p>
<p>See you in Portland!</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/05/24/are-you-ready-for-portland-code-camp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
