<?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>Tue, 16 Mar 2010 04:00:13 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<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>
		<item>
		<title>Implementing TeamCity for .NET Projects, Part 3: Running Tests, Nightly Builds, and Creating Artifacts</title>
		<link>http://elegantcode.com/2009/05/19/implementing-teamcity-for-net-projects-part-3-running-tests-nightly-builds-and-creating-artifacts/</link>
		<comments>http://elegantcode.com/2009/05/19/implementing-teamcity-for-net-projects-part-3-running-tests-nightly-builds-and-creating-artifacts/#comments</comments>
		<pubDate>Wed, 20 May 2009 02:43:06 +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/05/19/implementing-teamcity-for-net-projects-part-3-running-tests-nightly-builds-and-creating-artifacts/</guid>
		<description><![CDATA[For more information on this series, please see the introductory post.&#160; This post also assumes that you have completed parts 1 and 2.
With our basic solution build, we want to start running our unit tests on every check-in, create a nightly build (that runs both unit and integration tests), and generate some artifacts.
Running Tests
First things [...]]]></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>.&#160; 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> and <a title="Triggering Builds" href="http://codeprogression.blogspot.com/2009/04/implementing-teamcity-for-net-projects_15.html" target="_blank">2</a>.</em></p>
<p>With our basic solution build, we want to start running our unit tests on every check-in, create a nightly build (that runs both unit and integration tests), and generate some artifacts.</p>
<h4>Running Tests</h4>
<p>First things first, lets get the tests running.&#160; Open the current build configuration and select the build runner navigation link (it should say <strong><em>Runner: sln2008</em></strong>).&#160; On the build runner page, select NUnit 2.4.8 from the <strong>NUnit runner</strong> combo box.&#160; Add the path to the unit test assembly in the assembly text box.&#160; For our solution, the path is: <em>**/bin/debug/AdventureMVC.Tests.dll</em> .&#160; As you can see, this is using an MSBuild wildcard format to find the correct assembly.&#160; It is unnecessary to point to the full path.</p>
<p><a href="http://lh4.ggpht.com/_bGTiQEGe9PE/SetjgwktTsI/AAAAAAAAADA/E0ppw9FdUzo/s1600-h/image%5B52%5D.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://lh3.ggpht.com/_bGTiQEGe9PE/SetjhKkvslI/AAAAAAAAADE/zpUn6lBeUEM/image_thumb%5B36%5D.png?imgmax=800" width="404" height="105" /></a> </p>
<p>Save your changes.</p>
<p>Now, when your builds run, you should get a new status indicator showing how many tests passed.&#160; </p>
<p><a href="http://lh3.ggpht.com/_bGTiQEGe9PE/SetjhNlrXKI/AAAAAAAAADI/iawoT7Sr61A/s1600-h/image%5B7%5D.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://lh6.ggpht.com/_bGTiQEGe9PE/Setjhg4Id5I/AAAAAAAAADM/gFqKNfaGdpg/image_thumb%5B3%5D.png?imgmax=800" width="155" height="38" /></a> </p>
<p>If you click on the status, you will also see a new tab on the build results page showing the test information.</p>
<p><a href="http://lh6.ggpht.com/_bGTiQEGe9PE/SetjhrMw1XI/AAAAAAAAADQ/nYTHrbBltP8/s1600-h/image%5B10%5D.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://lh4.ggpht.com/_bGTiQEGe9PE/Setjh-t9hxI/AAAAAAAAADU/36RV_RBw4yI/image_thumb%5B4%5D.png?imgmax=800" width="244" height="82" /></a> <a href="http://lh5.ggpht.com/_bGTiQEGe9PE/Setjicm4mLI/AAAAAAAAADY/DTvKZhmg6SM/s1600-h/image%5B14%5D.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://lh6.ggpht.com/_bGTiQEGe9PE/SetjimGUQUI/AAAAAAAAADc/oPMY_29kw6g/image_thumb%5B6%5D.png?imgmax=800" width="644" height="102" /></a> </p>
<h4>Nightly Builds (with integration tests)</h4>
<p>Now that we have our <a href="http://lh4.ggpht.com/_bGTiQEGe9PE/Setjiz2NBUI/AAAAAAAAADg/5VU1vYlDtdY/s1600-h/image%5B19%5D.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="image" border="0" alt="image" align="right" src="http://lh4.ggpht.com/_bGTiQEGe9PE/SetjjCvcAYI/AAAAAAAAADk/8ofZ3QyJYhI/image_thumb%5B12%5D.png?imgmax=800" width="244" height="127" /></a>unit tests running on every check-in, let’s create a nightly build.&#160; Open the current build configuration.&#160; Make a copy of the build by clicking on the <strong><em>Copy </em></strong>button on the right-hand side of the page.&#160; </p>
<p>Rename the new configuration as you see fit.&#160; I will use<em><strong> </strong>Nightly Build</em>. </p>
<p><a href="http://lh5.ggpht.com/_bGTiQEGe9PE/SetjjQJQOQI/AAAAAAAAADo/YJ79CaPIpns/s1600-h/image%5B26%5D.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://lh3.ggpht.com/_bGTiQEGe9PE/Setjjo_10PI/AAAAAAAAADs/proSJBVodPI/image_thumb%5B17%5D.png?imgmax=800" width="304" height="119" /></a> </p>
<p>Select the build runner link.&#160; Add the integration test assembly to the test assembly text box. </p>
<p><a href="http://lh6.ggpht.com/_bGTiQEGe9PE/Setjj1z70vI/AAAAAAAAADw/41gX9Pi9wRY/s1600-h/image%5B32%5D.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://lh3.ggpht.com/_bGTiQEGe9PE/SetjkMgr1wI/AAAAAAAAAD0/WyXdq06KULE/image_thumb%5B21%5D.png?imgmax=800" width="504" height="40" /></a> </p>
<p>Save your changes.</p>
<p>Select the <strong><em>Build triggering </em></strong>link.&#160; Deselect the check box.&#160; On the <strong><em><a href="http://lh4.ggpht.com/_bGTiQEGe9PE/SetjkcgPL1I/AAAAAAAAAD4/omaSboacWV8/s1600-h/image%5B36%5D.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="image" border="0" alt="image" align="right" src="http://lh6.ggpht.com/_bGTiQEGe9PE/SetjkuHwjkI/AAAAAAAAAD8/SHagt8uJOUY/image_thumb%5B23%5D.png?imgmax=800" width="244" height="106" /></a></em></strong><strong><em>Schedule</em></strong> tab, click on <strong><em>Add time trigger </em></strong>and configure your nightly build time. Save your changes.&#160; (You can test the build at this point by clicking on the Run button.)</p>
<h4>Creating Artifacts</h4>
<p>We want to make the compiled website readily available, so we are going to create some artifacts.&#160; Getting at the precompiled website through the file system is inconvenient.</p>
<blockquote><p><em>If the example solution contained a website, compiling the solution would create a precompiled website.&#160; Since the example solution contains a web application project (specifically an ASP.NET MVC application project), I had to add a post-build event to create the precompiled site.&#160; Check the AdventureMVC project properties to see the syntax.</em></p>
</blockquote>
<p>On the Nightly Build configuration page, select the <strong><em>General Settings</em></strong> link.&#160; In the Artifacts text box, type: <em>PrecompiledWeb\Web=&gt;PrecompiledWeb</em>.&#160; Save your changes.</p>
<p><a href="http://lh6.ggpht.com/_bGTiQEGe9PE/Setjk8cDnOI/AAAAAAAAAEA/OkE1pau7wSc/s1600-h/image%5B53%5D.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://lh3.ggpht.com/_bGTiQEGe9PE/SetjlBmHeHI/AAAAAAAAAEE/6bqbz9nJxhc/image_thumb%5B38%5D.png?imgmax=800" width="636" height="50" /></a>&#160;</p>
<p>Now when you run your build, you should see an Artifacts dropdown link in the status line of the build.&#160; </p>
<p><a href="http://lh5.ggpht.com/_bGTiQEGe9PE/SetjlDht8SI/AAAAAAAAAEI/bXBDD6UQiko/s1600-h/image%5B47%5D.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="image" border="0" alt="image" src="http://lh4.ggpht.com/_bGTiQEGe9PE/SetjlXLjzNI/AAAAAAAAAEM/i9GFounB_RI/image_thumb%5B33%5D.png?imgmax=800" width="228" height="107" /></a></p>
<p>When you click on the build status, the status page now has an artifacts tab.&#160;&#160; </p>
<p><a href="http://lh3.ggpht.com/_bGTiQEGe9PE/Setjl-No3mI/AAAAAAAAAEQ/hyo0hHdeiHg/s1600-h/image%5B51%5D.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://lh3.ggpht.com/_bGTiQEGe9PE/SetjmFcHx-I/AAAAAAAAAEU/sf8eWf8RcUM/image_thumb%5B35%5D.png?imgmax=800" width="404" height="62" /></a> </p>
<p>Not only do you have the ability to download the individual files, you can now use these artifacts in other build configurations…but that is for another post.</p>
<p>Originally posted on <a href="http://codeprogression.com">CodeProgression.com</a> on April 19, 2009</p>
</p>
<hr />
<h4>Upcoming posts: </h4>
<ul>
<li>
<p>Build scripts: We need some additional functionality that the basic solution runner doesn’t provide, such as zipping up artifacts.</p>
</li>
<li>
<p>Setting up notifications: We will look at the different options for notifications, such as email and the tray notifier.</p>
</li>
<li>
<p>Deployment: Using TeamCity and build scripts to update different deployment environments.</p>
<ul></ul>
</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></p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/05/19/implementing-teamcity-for-net-projects-part-3-running-tests-nightly-builds-and-creating-artifacts/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Implementing TeamCity for .NET Projects, Part 2: Triggering Builds</title>
		<link>http://elegantcode.com/2009/05/19/implementing-teamcity-for-net-projects-part-2-triggering-builds/</link>
		<comments>http://elegantcode.com/2009/05/19/implementing-teamcity-for-net-projects-part-2-triggering-builds/#comments</comments>
		<pubDate>Wed, 20 May 2009 02:40:02 +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/05/19/implementing-teamcity-for-net-projects-part-2-triggering-builds/</guid>
		<description><![CDATA[For more information on this series, please see the introductory post.
Why Continuous Integration?
The benefit of continuous integration, according to Martin Fowler, is reduced risk.&#160; Reduced risk is accomplished through a quick feedback cycle.&#160; The longer you defer integration, the more difficult integration becomes.&#160; If you integrate automated testing into your integration cycle, you can further [...]]]></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>.</em></p>
<h4>Why Continuous Integration?</h4>
<p>The benefit of continuous integration, <a href="http://www.martinfowler.com/articles/continuousIntegration.html#BenefitsOfContinuousIntegration">according to Martin Fowler</a>, is reduced risk.&#160; Reduced risk is accomplished through a quick feedback cycle.&#160; The longer you defer integration, the more difficult integration becomes.&#160; If you integrate automated testing into your integration cycle, you can further reduce your risk.</p>
<h4>Continuous Integration with TeamCity (VCS Triggers)</h4>
<p>TeamCity has four build trigger options:</p>
<ol>
<li>VCS Triggers: Triggers a build when files are checked into source control. </li>
<li>Schedule: Triggers a build on a predetermined schedule. </li>
<li>Dependencies: Triggers a build when another build completes successfully. </li>
<li>Other Triggers: Triggers a build if previous build fails. </li>
</ol>
<h5></h5>
<p>VCS triggers are analogous to continuous integration.&#160; Check in files to source control and a build is started.&#160; Enabling continuous integration in TeamCity takes only a few clicks to configure.</p>
<p><a href="http://lh3.ggpht.com/_bGTiQEGe9PE/SeWl4q9bSzI/AAAAAAAAACY/urgxFaaqw5I/s1600-h/image%5B9%5D.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="image" border="0" alt="image" align="left" src="http://lh3.ggpht.com/_bGTiQEGe9PE/SeWl5N0ZuLI/AAAAAAAAACc/_cnWwfdjkuU/image_thumb%5B6%5D.png?imgmax=800" width="244" height="145" /></a>Lets get started. Click the arrow next to the build configuration we completed in the <a href="http://codeprogression.blogspot.com/2009/04/implementing-teamcity-for-net-projects.html" target="_blank">last post</a>. Select <em>Edit Settings</em>. </p>
<p>&#160;</p>
<p><em><a href="http://lh5.ggpht.com/_bGTiQEGe9PE/SeWl5Jt3KQI/AAAAAAAAACg/lGbRWgQTlVQ/s1600-h/image19.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="image" border="0" alt="image" align="right" src="http://lh6.ggpht.com/_bGTiQEGe9PE/SeWl5RsvJ_I/AAAAAAAAACk/Zj8kcKy0hM4/image_thumb21.png?imgmax=800" width="244" height="124" /></a></em><em></em></p>
<p><em><a href="http://lh5.ggpht.com/_bGTiQEGe9PE/SeWl5Jt3KQI/AAAAAAAAACg/lGbRWgQTlVQ/s1600-h/image19.png"></a></em></p>
<p>&#160;</p>
<p>On the right side of the build configuration screen, you will see a list of <em>Build Configuration Steps</em>.&#160; Select the<em> Build Triggering </em>step.&#160; </p>
</p>
<p>Select the checkbox labeled <strong>Enable triggering when files are checked into VCS</strong>.&#160; </p>
<p><a href="http://lh5.ggpht.com/_bGTiQEGe9PE/SeWl5n6JYaI/AAAAAAAAACo/GNlmnlydViQ/s1600-h/image%5B14%5D.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://lh5.ggpht.com/_bGTiQEGe9PE/SeWl5zb4cbI/AAAAAAAAACs/SoTzNoAph_w/image_thumb%5B9%5D.png?imgmax=800" width="244" height="46" /></a> </p>
<p><em>At this point, you can save your changes and you will have enabled continuous integration.&#160; The quiet period and trigger rules (explained below)&#160; fine-tune the behavior of the build trigger.</em></p>
<p>Once checked, an option to set a quiet period is enabled.&#160; A quiet period is the length of time after a check-in which TeamCity will wait before starting the build.&#160; If check-ins tend to come in waves, this can help keep the build queue short.&#160; (If you tend to forget to check in all your files or need to check in files from your IDE and file system, you may want to give yourself a short quiet period before triggering a build to allow for multiple check-ins.)<a href="http://lh4.ggpht.com/_bGTiQEGe9PE/SeWl6zbbiBI/AAAAAAAAACw/weZSzQaToqg/s1600-h/image23.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://lh3.ggpht.com/_bGTiQEGe9PE/SeWl7URsp9I/AAAAAAAAAC0/zcV9WOdDXxY/image_thumb23.png?imgmax=800" width="644" height="100" /></a> </p>
<p>However, if you configure too long of a quiet period with a project with a large team, the build may take too long to start, negating the benefits of continuous integration.&#160; I prefer to select <em>Do not use </em>or <em>Use default value (60 seconds)</em> for my projects.</p>
<p>Finally, you can exclude some check-ins from triggering the build by defining trigger patterns.&#160; Exclusions can be based on file paths, users, or a combination.&#160; For example, if your project team includes a technical writer who produces documentation, those check-ins probably do not affect build quality.&#160; Or, when you update your build scripts, those changes may not need to trigger a build either (see example below).&#160; <em>For the purposes of the example solution, you may define the <strong>–:*.build</strong> pattern, even though we haven’t started using build scripts yet.</em></p>
<p>&#160;<a href="http://lh3.ggpht.com/_bGTiQEGe9PE/SeWl7hHHTDI/AAAAAAAAAC4/Ei2jbubqoAI/s1600-h/image%5B16%5D.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="image" border="0" alt="image" src="http://lh5.ggpht.com/_bGTiQEGe9PE/SeWl7wTkm1I/AAAAAAAAAC8/sr1EYSRph9Y/image_thumb%5B11%5D.png?imgmax=800" width="316" height="88" /></a></p>
<p>Defining a trigger pattern is fairly straightforward. The pattern is:    <br /><strong>+|-:[user][VCS root][path]      <br /></strong>Defining a +: rule removes the include all rule, allowing a very fine-grade include path. Defining a –: rule excludes the defined path from triggering a build.&#160; For more information, see the <a href="http://www.jetbrains.net/confluence/display/TCD4/Configuring+VCS+Triggers" target="_blank">documentation</a>.</p>
<p>Finish by saving your changes and returning to the main page.&#160; Update and check in a project file and you can watch TeamCity start a new build process.</p>
<p>&#160;<strong><em>Congratulations! You have just enabled continuous integration with TeamCity!</em></strong></p>
<h6>Originally posted on <a href="http://codeprogression.com">CodeProgression.com</a> on April 15, 2009</h6>
</p>
<hr />
<h4>Upcoming posts: <a href="http://elegantcode.com/2009/05/19/implementing-teamcity-for-net-projects-part-3-running-tests-nightly-builds-and-creating-artifacts/" target="_blank">Creating artifacts and nightly builds</a></h4>
</p>
<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></p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/05/19/implementing-teamcity-for-net-projects-part-2-triggering-builds/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
