<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="http://feeds.mozingo.net/~d/styles/rss2full.xsl" type="text/xsl" media="screen"?><?xml-stylesheet href="http://feeds.mozingo.net/~d/styles/itemcontent.css" type="text/css" media="screen"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Taller Code</title>
	
	<link>http://darrell.mozingo.net</link>
	<description>Darrell Mozingo's blog on .NET and development in general</description>
	<pubDate>Fri, 26 Sep 2008 19:31:37 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.5</generator>
	<language>en</language>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.mozingo.net/TallerCode" type="application/rss+xml" /><item>
		<title>Automated Builds &amp; Continuous Integration - Part 2</title>
		<link>http://feeds.mozingo.net/~r/TallerCode/~3/404078559/</link>
		<comments>http://darrell.mozingo.net/2008/09/26/automated-builds-continuous-integration-part-2/#comments</comments>
		<pubDate>Fri, 26 Sep 2008 19:29:19 +0000</pubDate>
		<dc:creator>Darrell Mozingo</dc:creator>
		
		<category><![CDATA[Build Management]]></category>

		<guid isPermaLink="false">http://darrell.mozingo.net/?p=25</guid>
		<description><![CDATA[In Part 1 I talked, quite generally, about what automated builds and continuous integration servers are. In this part I&#8217;ll walk you through setting up a simple automated build script for your company&#8217;s extension library.
Setting Up Your Project
For a while now I&#8217;ve been creating an Internal folder under the main project, which has folders for [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://darrell.mozingo.net/2008/08/28/automated-builds-continuous-integration-part-1/">Part 1</a> I talked, quite generally, about what automated builds and continuous integration servers are. In this part I&#8217;ll walk you through setting up a simple automated build script for your company&#8217;s extension library.</p>
<h2>Setting Up Your Project</h2>
<p><img class="alignright" style="float: right;" src="http://darrell.mozingo.net/wp-content/uploads/2008/09/projectexplorer-buildscripts.png" alt="Project Explorer" title="Build Script Project Explorer" />For a while now I&#8217;ve been creating an <code>Internal</code> folder under the main project, which has folders for the Tools (NAnt, MbUnit, etc), documentation (if needed), libraries, etc. This has been working out well, but I&#8217;m probably going to switch the method used by many open source projects, where the top level directory has a <code>src</code> (for your actual source code), <code>lib</code> (for reference assemblies), and <code>bin</code> (for tools) folders. See the image at the right for my current layout.</p>
<p>Notice that those tools, NAnt/MbUnit/NCover/etc, are actually checked into the project. They&#8217;re not sitting in my Program Files directory or on some network share. Each project has a copy of all the tools it needs (and everything those tools need to run), which enables not only the build server to pull down everything it needs from source control, but new developers as well. One checkout command and they&#8217;re good to build and run the project. This is <b>definitely</b> a time saver, and, if nothing else, I highly recommend implementing this practice or one similar.</p>
<p>For reference, I&#8217;ll be using NAnt 0.85 (available <a href="http://sourceforge.net/project/downloading.php?groupname=nant&#038;filename=nant-0.85-bin.zip&#038;use_mirror=internap">here</a>), MbUnit 2.4.197 (available <a href="http://mb-unit.googlecode.com/files/MbUnit-2.4.197.exe">here</a>), NCover 1.5.8 (one of the last free versions available before they became a <a href="http://www.ncover.com/">commercial product</a> - and while this version doesn&#8217;t support some of the newer stuff in C# 3 as their commercial version does, it&#8217;ll work for our purposes - available <a href="http://www.ncover.com/download/download_file?filename=NCover-1.5.8.zip">here</a>), and NCoverExplorer 1.4.0.7 (which is now also commercial and integrated into NCover, but I have the latest freely copy available <a href="http://darrell.mozingo.net/wp-content/uploads/2008/09/NCoverExplorer-1.4.0.7.zip">here</a>).</p>
<h2>The Build Script</h2>
<p>Create a file in the root of your project, to hold the actual NAnt configuration to build your project and run its unit tests. I usually name the file <code><i>ProjectName</i>.build</code>.</p>
<p>Please note that all of the empty XML tags in the example below can be shortened to the normal <code>&lt;tag attribute="" /&gt;</code> format, but my syntax highlighter is being a butt and adding the closing tags no matter what I do, so I just added them in the proper place myself in this post. The code in the downloadable solution at the end of the post should be formatted normally.</p>
<p>A couple of quick pointers for working with NAnt:</p>
<ol>
<li>
  The word artifacts, as in most build systems, refers to anything produced by the build system itself, such as reports, executables, installation files, documentation, etc.
  </li>
<li>
  Variable declaration/use:</p>
<pre name="code" class="xml:nocontrols" cols="80" rows="10">
  <property name="build.dir" value="bin"></property>
  <delete dir="${build.dir}"></delete>
  </pre>
</li>
<li>
  Method declaration (normally called <code>targets</code>):</p>
<pre name="code" class="xml:nocontrols" cols="80" rows="10">
  <target name="compile" description="Compiles the project using MSBuild."></target>
  </pre>
</li>
<li>
  Outputting text to the screen:</p>
<pre name="code" class="xml:nocontrols" cols="80" rows="10">
  <echo message="Outputting this message to the screen."></echo>
  </pre>
</li>
</ol>
<p>You start a NAnt build script with <code>&lt;project /&gt;</code> tags, which specifies the project name and the default target (method) to run when one isn&#8217;t specified by the calling application:</p>
<pre name="code" class="xml:nocontrols" cols="80" rows="10">
<project name="MyExtensions" default="build-server" 
	xmlns="http://nant.sf.net/release/0.85/nant.xsd">
</project>
</pre>
<p>Now for the meat of the build script. Let&#8217;s start off with a few basic parameter declarations:</p>
<pre name="code" class="xml:nocontrols" cols="80" rows="10">
<property name="build.project" value="MyExtensions"></property>
<property name="build.dir" value="${build.project}\bin"></property>
<property name="build.config" value="Release"></property>
<property name="build.fullPath" value="${build.dir}\${build.config}"></property>
<property name="build.toolPath" 
	value="C:\WINDOWS\Microsoft.NET\Framework\v3.5\msbuild.exe"></property>
<property name="tools.dir" value="${build.project}\Internal\Tools"></property>
<property name="build.testBuildDir" value="${build.project}.UnitTests\bin"></property>
<property name="reports.dir" value="${build.dir}\Reports"></property>
<property name="reports.ncover" value="${reports.dir}\NCover-Report.xml"></property>
<property name="build.outputPath" value="\\fileServer\Assemblies\MyExtensions"></property>
</pre>
<p>These specify the path to the build directory, where the MsBuild executable is on the machine (which we&#8217;ll use in a later section), where the tools are located, and where to output various artifacts. All of these paths are relative to where your build script is located, so if you placed it in your root folder with your Visual Studio solution file, these paths should work out.</p>
<p>Next we&#8217;ll specify a four targets (methods); two to act as convenience targets that call out to other targets, one that cleans the current build artifacts, and the last one that compiles the project:</p>
<pre name="code" class="xml:nocontrols" cols="80" rows="10">
	<target name="build-server" depends="clean, compile, unitTests, ncoverexplorer-report publishOutput"
		description="In addition to the normal full build, it copies the solution output to a specified network share."></target>

	<target name="full-build" depends="clean, compile, unitTests, ncoverexplorer-report"
		description="Does a full build of the project and runs unit tests."></target>

	<target name="clean" description="Destroys the directory where all assemblies/reports are generated.">
		<delete 
			dir="${build.dir}" 
			if="${directory::exists(property::get-value('build.dir'))}" 
			failonerror="false"></delete>

		<delete
			dir="${build.testBuildDir}"
			if="${directory::exists(property::get-value('build.testBuildDir'))}"
			failonerror="false"></delete>
	</target>

	<target name="compile" description="Compiles the project using the MSBuild executable.">
		<echo message="Using MSBuild to build configuration: ${build.config}"></echo>

		<exec program="${build.toolPath}"
			commandline="${build.project}.sln /p:Configuration=${build.config} /nologo /noconsolelogger /noautoresponse"></exec>
	</target>
</pre>
<p>Notice that the <code>build-server</code> and <code>full-build</code> targets use the <code>depends</code> attribute, which will call out to each of the specified targets, in order. The <code>build-server</code> and <code>full-build</code> targets are identical except for the last target call, <code>publishOutput</code>. Discussed below, this target will copy the library&#8217;s build outputs to our file share for everyone to access. Since we only want to do this on the build server, and not when ran locally, we&#8217;ll name the target differently. </p>
<p>The <code>clean</code> target just deletes the bin directory if it exists, and the <code>compile</code> target will call out to the actual MsBuild.exe to compile the solution.</p>
<p>There are built-in NAnt tasks (or available in the <a href="http://nantcontrib.sourceforge.net/">NAnt Contrib</a> project) that will compile solutions and do a few of the other tasks that I&#8217;m doing by hand, such as running NUnit and building installers. I prefer this method, though, for more control over what&#8217;s getting called and less breakage when upgrading various tools.</p>
<p>OK, so I go and say that, and now show you the <code>unitTests</code> target, which uses a custom NCover task. I made an exception for this step, since NCover normally requires a special COM object to be registered before it&#8217;s ran, which I had no interest of doing through a script. The custom task takes care of all that:</p>
<pre name="code" class="xml:nocontrols" cols="80" rows="10">
	<target name="unitTests" description="Runs all needed unit tests with MbUnit and checks coverage with NCover.">
		<mkdir 
			dir="${reports.dir}" 
			unless="${directory::exists(property::get-value('reports.dir'))}"></mkdir>

		<!-- Call NCover, which will call MbUnit to run the tests. 
			While MbUnit runs, NCover does its work.

				- To add additional unit test libraries, add the full path to the unit test DLL
				   at the end of the commandLineArgs attribute, separating it with a space 
				   and being mindful of the ${build.config} variable. 
				   Do NOT wrap this line, as NCover will fail.

				- To add a new assembly you want to check coverage on, add the assembly 
				   name at the end of the assemblyList attribute, separating them with a 
				   semi-colon.  -->
		<ncover program="${tools.dir}\NCover\NCover.Console.exe"
				commandLineExe="${tools.dir}\MbUnit\MbUnit.Cons.exe"
				coverageFile="${reports.ncover}"
				logFile="${reports.dir}\NCover-Log.log" 
				assemblyList="${build.project}" 
				commandLineArgs="/report-folder:${reports.dir} /report-name-format:MbUnit-Report /report-type:Xml ${build.testBuildDir}\${build.config}\${build.project}.UnitTests.dll"</ncover>
	</target>
</pre>
<p>As the comment says, the NCover task will set itself up as needed, then call MbUnit to run through the unit tests, while it basically keeps an eye on what parts of your code are getting called. NCover then produces a report listing each function point (usually equal to a line in your code) that was hit while the unit tests ran. More function points being called == higher code coverage percentage.</p>
<p>This next target will call out to NCoverExplorer, which simply takes in the NCover report made in the previous target and generates a report of its own for use in its GUI app, along with a nice little HTML report for display in CruiseControl.NET&#8217;s interface later on:</p>
<pre name="code" class="xml:nocontrols" cols="80" rows="10">
	<target name="ncoverexplorer-report" description="Produces a condensed report in XML format from NCover.">
		<exec program="NCoverExplorer.Console.exe" basedir="${tools.dir}\NCoverExplorer">
			<arg value="/xml:${reports.dir}\NCoverExplorer-Report.xml"></arg>
			<arg value="/html:${reports.dir}\NCoverExplorer-Report.html"></arg>
			<arg value="/project:&quot;${build.project}&quot;"</arg>

			<!-- Minimum coverage for a "passed" test in %. -->
			<arg value="/minCoverage:95"></arg>

			<!-- Show the highest level of detail in the report. -->
			<arg value="/report:5"></arg>

			<arg value="${reports.ncover}"></arg>
		</exec>
	</target>
</pre>
<p>Now we simply copy the project&#8217;s output (or in our case, the .dll from the extension library) to an output directory. I usually have it copy it to a commonly accessible file share for easier access:</p>
<pre name="code" class="xml:nocontrols" cols="80" rows="10">
	<target name="publishOutput" description="Publishes the solution's output by copying it to a specified directory.">
		<copy todir="${build.outputPath}" overwrite="true">
			<fileset basedir="${build.fullPath}">
				<include name="${build.project}.dll"></include>
				<include name="${build.project}.pdb"></include>
			</fileset>
		</copy>
	</target>
</pre>
<p>An optional last step is to create a batch file in the root of the project which simply calls out to the NAnt executable, passing in your new build file as a parameter. This batch file can then be ran to kick off the full build script by calling <code>build.bat full-build</code>:</p>
<pre name="code" class="c#:nocontrols" cols="80" rows="10">
@MyExtensions\Internal\Tools\NAnt\NAnt.exe -buildfile:MyExtensions.build %*
</pre>
<p>Which runs through and results in a nice little &#8220;BUILD SUCCEEDED&#8221; message:</p>
<p><img src="http://darrell.mozingo.net/wp-content/uploads/2008/09/buildresult-buildscripts.png" alt="Build Script" title="Build Script Running" /></p>
<p>Gives me the warm and fuzzies every time.</p>
<p>Well, that&#8217;s pretty much it. A very basic build script, but it gets the job done. I&#8217;d recommend poking around the build scripts for more popular open source projects to get better idea of what these scripts are really capable of automating for you. Take a look at <a href="http://ninject.org/">Ninject&#8217;s</a> for building a public framework that targets different platforms, or <a href="http://subtextproject.com/">Subtext&#8217;s</a> for building a website solution.</p>
<p>A skeleton project setup with this build script, complete with the needed tools and everything, can be downloaded <a href="http://darrell.mozingo.net/wp-content/uploads/2008/09/MyExtensions-BuildScriptsAndCI-Part2.zip">here</a>.</p>
<p>In Part 3 I&#8217;ll go over setting up a basic build server using Cruise Control.NET. The build server basically just calls out to this build script, so, thankfully, the bulk of the job is already done.</p>
]]></content:encoded>
			<wfw:commentRss>http://darrell.mozingo.net/2008/09/26/automated-builds-continuous-integration-part-2/feed/</wfw:commentRss>
		<feedburner:origLink>http://darrell.mozingo.net/2008/09/26/automated-builds-continuous-integration-part-2/</feedburner:origLink></item>
		<item>
		<title>Automated Builds &amp; Continuous Integration - Part 1</title>
		<link>http://feeds.mozingo.net/~r/TallerCode/~3/377359526/</link>
		<comments>http://darrell.mozingo.net/2008/08/28/automated-builds-continuous-integration-part-1/#comments</comments>
		<pubDate>Thu, 28 Aug 2008 18:16:45 +0000</pubDate>
		<dc:creator>Darrell Mozingo</dc:creator>
		
		<category><![CDATA[Build Management]]></category>

		<guid isPermaLink="false">http://darrell.mozingo.net/?p=15</guid>
		<description><![CDATA[Ah yes, automated build scripts and continuous integration servers. They form the foundation of any software project, or rather they should, but how would one go about setting them up? Before we get to that, let&#8217;s differentiate a little first.
Build Scripts
These are simply scripts that another program parses and executes to build your project, usually [...]]]></description>
			<content:encoded><![CDATA[<p>Ah yes, automated build scripts and continuous integration servers. They form the foundation of any software project, or rather they should, but how would one go about setting them up? Before we get to that, let&#8217;s differentiate a little first.</p>
<h5>Build Scripts</h5>
<p>These are simply scripts that another program parses and executes to build your project, usually doing everything from wiping your build directory to running unit test and integration tests, to possibly creating and destroying test databases. Build scripts can range from simple batch files to more complex <a href="http://nant.sourceforge.net/">NAnt</a> scripts. </p>
<p>Actually, you may not realize it, but you&#8217;re probably using build scripts already. Starting with Visual Studio 2005, <a href="http://msdn.microsoft.com/en-us/library/wea2sca5(VS.80).aspx">MSBuild</a> has been used behind the scenes to automatically build your solution when you hit Build -> Build Solution. MSBuild can also be used independently in much the same way as NAnt scripts, and in fact many people consider these two build systems to be the most mature/robust for the .NET environment. They both consist of a lot of XML, though, so <a href="http://www.youtube.com/watch?v=uE9Dgp4zlPg">put on your goggles</a> before taking a gander at any examples. There&#8217;s also the <a href="http://www.ayende.com/Blog/archive/2007/09/22/Introducing-Boobs-Boo-Build-System.aspx">Boo Build System</a> (though I think its been renamed to Bake due to its original initials) that&#8217;s based on the Boo language, <a href="http://code.google.com/p/psake/">psake</a> based on Powershell, <a href="http://www.finalbuilder.com/">FinalBuilder</a> for a graphical approach, and <a href="http://rake.rubyforge.org/">rake</a> that&#8217;s built on Ruby, among many others.</p>
<p>So build script are read by a build system, and executed. Complicated batch scripts, basically. They can be run locally, and many people actually opt to run these scripts instead of using Visual Studio&#8217;s build command once they get a good script setup, or they can be run automatically by other programs. I haven&#8217;t gotten to the point of replacing Visual Studio&#8217;s build command yet, but I can see its benefits.</p>
<h5>Continuous Integration Servers</h5>
<p>These little beauties generally run on their own box, and can either poll your source code repository (in whatever form it may come, be it Visual Source Safe, Subversion, Git, etc.) or run on a schedule, basically kicking off your build script whenever it sees changes. For instance, if you check in an update, the build server will see that update, clean its local copy of source code, do a full update of the source code locally, then run the build script you normally run on your box, building the code and running all sorts of tests. It can then go a step further and start copying the output to a staging server for your customers or testing folks to take a sneak peek at.</p>
<p>Continuous Integration (CI) servers come in quite a few flavors. One of the more popular in the .NET world is <a href="http://confluence.public.thoughtworks.org/display/CCNET/Welcome+to+CruiseControl.NET">Cruise Control .NET</a> (CC.NET), though it too has a heavy reliance on XML. JetBrains (the guys that make ReSharper) have released <a href="http://www.jetbrains.com/teamcity/">TeamCity</a> as a free download (for up to 20 user accounts and build configurations, and 3 build agents), which has an awesome web interface and lets you get a server setup in no time. It has built in support for quite a few features, and even comes with a plug-in for Visual Studio that lets you run a fake build locally on your machine before doing a code check-in. There are quite a few other CI servers out there, but these are the only two I&#8217;ve had time to play around with.</p>
<h2>Setting Up a Build Script and CI Server</h2>
<p>New with C# 3.0 comes extension methods, which I&#8217;m sure everyone&#8217;s heard of, and I&#8217;m equally sure that everyone has a small collection of handy ones in some sort of extension library. This library is probably shared across projects, and any developer wishing to use it in their project needs to do a get latest from the source code repository, build the solution, find the compiled assembly on their machine, and copy the it into their project. This repeats if they want to update their project&#8217;s copy, too.</p>
<p>Seems like a lot of steps just to use or update the library, huh? Let&#8217;s tidy that up a little, by:</p>
<ol>
<li>Setting up a build script using NAnt, which will:</li>
<ul>
<li>Clean the /bin folder</li>
<li>Do a full recompile of the source code</li>
<li>Run FxCop to check for out of place coding standards</li>
<li>Run MbUnit (my testing framework of choice)</li>
<li>Run NCover (using the latest freely available copy)</li>
<li>Run NCoverExplorer, which will generate a neat little XML file you can use to graphically see your code coverage (again, using the latest freely available copy)</li>
<li>Be able to run locally on each developer&#8217;s machine, if they so choose</li>
</ul>
<li>Setting up a continuous integration server using Cruise Control .NET, which will:</li>
<ul>
<li>Both periodically poll the source control server for any new commits, along with just running at a set time every night</li>
<li>Clean its source code copy and run an update from the source control repository</li>
<li>Run the build script previously created</li>
<li>Email any developer that checked in code during this run with an update on the fail/pass status of the build</li>
<li>Allow any developer running a handy-dandy desktop app to instantly see the status of the build server (success, failure, building, etc)</li>
</ul>
</ol>
<p>Alright, alright, so this might not seem like it&#8217;ll really tidy up anything right now, just add a crap load of work to our plates, but trust me, it&#8217;s not as bad as it looks. A lot of this can be heavily templated across projects too, so once you cut your teeth on it, it&#8217;s tremendously easier to setup again going forward. </p>
<p>In <a href="http://darrell.mozingo.net/2008/09/26/automated-builds-continuous-integration-part-2/">Part 2</a>, I&#8217;ll talk about setting up the build script using NAnt.</p>
]]></content:encoded>
			<wfw:commentRss>http://darrell.mozingo.net/2008/08/28/automated-builds-continuous-integration-part-1/feed/</wfw:commentRss>
		<feedburner:origLink>http://darrell.mozingo.net/2008/08/28/automated-builds-continuous-integration-part-1/</feedburner:origLink></item>
		<item>
		<title>On Throwing Exceptions</title>
		<link>http://feeds.mozingo.net/~r/TallerCode/~3/365909331/</link>
		<comments>http://darrell.mozingo.net/2008/08/15/on-throwing-exceptions/#comments</comments>
		<pubDate>Fri, 15 Aug 2008 19:01:45 +0000</pubDate>
		<dc:creator>Darrell Mozingo</dc:creator>
		
		<category><![CDATA[Quickie]]></category>

		<guid isPermaLink="false">http://darrell.mozingo.net/?p=22</guid>
		<description><![CDATA[Don&#8217;t catch exceptions unless you&#8217;re prepared to do something meaningful about it, or add more useful information to the exception message/object. There&#8217;s nothing more annoying than seeing:

try
{
	SomeOperationThatThrowsAnException();
}
catch(Exception ex)
{
	throw;
}

Or:

try
{
	SomeOperationThatThrowsAnException();
}
catch(Exception ex)
{
	throw new Exception("Some Operation threw an exception");
}

Or anything else along those lines. They add nothing meaningful to the situation, and only aid to obfuscate the call stack [...]]]></description>
			<content:encoded><![CDATA[<p>Don&#8217;t catch exceptions unless you&#8217;re prepared to do something meaningful about it, or add more useful information to the exception message/object. There&#8217;s nothing more annoying than seeing:</p>
<pre name="code" class="c#:nocontrols" cols="80" rows="10">
try
{
	SomeOperationThatThrowsAnException();
}
catch(Exception ex)
{
	throw;
}
</pre>
<p>Or:</p>
<pre name="code" class="c#:nocontrols" cols="80" rows="10">
try
{
	SomeOperationThatThrowsAnException();
}
catch(Exception ex)
{
	throw new Exception("Some Operation threw an exception");
}
</pre>
<p>Or anything else along those lines. They add nothing meaningful to the situation, and only aid to obfuscate the call stack when debugging. The only reasonable time you should catch an exception, in my opinion, is to somehow recover the operation, or add meaning and context to it. For example:</p>
<pre name="code" class="c#:nocontrols" cols="80" rows="10">
int userID = 20;   // Already a class member or passed in as a parameter.

try
{
	SomeOperationThatThrowsAnException(userID);
}
catch(Exception ex)
{
	throw new Exception("Couldn't do an operation on userID \"" + userID + "\".", ex);
}
</pre>
<p>Granted, there should probably be a logging facility setup to handle this type of stuff, or a more robust exception framework that will dump all needed local variables, but you get the idea. The exception is essentially being rethrown, but with more context to help debug the problem later on.</p>
<p>Also, remember that you can have a try/finally block with no catch. There&#8217;s no need to throw a catch block in there and rethrow just to get the benefits of cleaning up your resources. This is perfectly legal:</p>
<pre name="code" class="c#:nocontrols" cols="80" rows="10">
try
{
	SomeOperationThatThrowsAnException();
}
finally
{
	// Cleanup resources.
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://darrell.mozingo.net/2008/08/15/on-throwing-exceptions/feed/</wfw:commentRss>
		<feedburner:origLink>http://darrell.mozingo.net/2008/08/15/on-throwing-exceptions/</feedburner:origLink></item>
		<item>
		<title>Success Story</title>
		<link>http://feeds.mozingo.net/~r/TallerCode/~3/339203807/</link>
		<comments>http://darrell.mozingo.net/2008/07/18/success-story/#comments</comments>
		<pubDate>Fri, 18 Jul 2008 17:45:55 +0000</pubDate>
		<dc:creator>Darrell Mozingo</dc:creator>
		
		<category><![CDATA[Quickie]]></category>

		<guid isPermaLink="false">http://darrell.mozingo.net/?p=20</guid>
		<description><![CDATA[Devlicio.us was holding a contest on personal success stories, so I entered with a short one about my current job. The environment and whole attitude of everyone here has changed dramatically in the recent past, and I&#8217;m quite proud to share the story.
Here&#8217;s the entry, which got me a second place finish:
http://devlicio.us/blogs/sergio_pereira/archive/2008/07/07/doing-a-180-in-a-matter-of-months.aspx
]]></description>
			<content:encoded><![CDATA[<p>Devlicio.us was holding a contest on personal success stories, so I entered with a short one about my current job. The environment and whole attitude of everyone here has changed <strong>dramatically</strong> in the recent past, and I&#8217;m quite proud to share the story.</p>
<p>Here&#8217;s the entry, which got me a second place finish:</p>
<p><a href="http://devlicio.us/blogs/sergio_pereira/archive/2008/07/07/doing-a-180-in-a-matter-of-months.aspx">http://devlicio.us/blogs/sergio_pereira/archive/2008/07/07/doing-a-180-in-a-matter-of-months.aspx</a></p>
]]></content:encoded>
			<wfw:commentRss>http://darrell.mozingo.net/2008/07/18/success-story/feed/</wfw:commentRss>
		<feedburner:origLink>http://darrell.mozingo.net/2008/07/18/success-story/</feedburner:origLink></item>
		<item>
		<title>Automatically Run Your Unit Tests During Compilation</title>
		<link>http://feeds.mozingo.net/~r/TallerCode/~3/323427185/</link>
		<comments>http://darrell.mozingo.net/2008/06/30/automatically-run-your-unit-tests-during-compilation/#comments</comments>
		<pubDate>Mon, 30 Jun 2008 18:06:56 +0000</pubDate>
		<dc:creator>Darrell Mozingo</dc:creator>
		
		<category><![CDATA[Quickie]]></category>

		<guid isPermaLink="false">http://darrell.mozingo.net/?p=16</guid>
		<description><![CDATA[We have a steadily growing collection of small extension methods (including the usual .IsNullOrEmpty(), .To&#60;int&#62;(), etc.), along with corresponding unit tests, setup at my work. I spent some time a few weeks ago increasing the test coverage from around 70% to 100%, along with making the unit tests a bit more robust.
After setting up a [...]]]></description>
			<content:encoded><![CDATA[<p>We have a steadily growing collection of small extension methods (including the usual <code>.IsNullOrEmpty()</code>, <code>.To&lt;int&gt;()</code>, etc.), along with corresponding unit tests, setup at my work. I spent some time a few weeks ago increasing the test coverage from around 70% to 100%, along with making the unit tests a bit more robust.</p>
<p>After setting up a build script for the project and adding it to our continuous integration server (which I&#8217;ll blog about shortly), I found a few check-ins that were breaking old unit tests. Emails were automatically sent out, by the CI server, about the failed tests and broken builds, but it turns out too many of us were forgetting to run the unit tests before doing our check-in (obviously). We don&#8217;t have <a href="http://www.testdriven.net/">TestDriven.Net</a> or Resharper - though we&#8217;ll likely be ordering copies of the later any day now - so we have no easy way of running the tests besides the standard MbUnit GUI. Yuck.</p>
<p>A few days later I ran into this helpful piece of information, I think perhaps from JP Boodhoo, though I&#8217;m not positive. Anyway, if you have a separate assembly for your unit tests, simply go to the property page of that project, click the &#8220;Build Events&#8221; tab along the left, and enter this in for the post-build event:</p>
<p><code>"$(ProjectDir)..\UtilityLibrary.Core\Internal\Tools\MbUnit\MbUnit.Cons.exe" "$(TargetPath)"</code></p>
<p>This statement assumes you have your project checked out to something like C:\MyProjects\UtilityLibrary, and under there you have UtilityLibrary.Core for your actual code, and UtilityLibrary.UnitTests for, well, your unit tests. This command starts in the UnitTests forlder, goes up a directory (into C:\MyProjects\UtilityLibrary) and right back into the Core folder, which has the MbUnit library/program in it. If your situation is at all different, you&#8217;ll have to adjust this command accordingly, but it&#8217;s a good start.</p>
<p>Now your unit tests will be ran as a step in compiling your solution, and the compilation will fail if any of the unit tests fail:</p>
<p><img src="http://darrell.mozingo.net/wp-content/uploads/2008/06/compilation-test-unit-run.png" alt="" title="Running Unit Tests on Compilation" width="500" height="60" class="alignleft size-full wp-image-18" /></p>
<p>Useful for smaller utility projects like this, but I imagine it&#8217;d become a pain in the ass for larger projects that take a bit of time to compile on there own, never mind having to run the unit tests on top of that every time. Sometimes you just want to see if the code compiles, not necessarily run all the tests too.</p>
]]></content:encoded>
			<wfw:commentRss>http://darrell.mozingo.net/2008/06/30/automatically-run-your-unit-tests-during-compilation/feed/</wfw:commentRss>
		<feedburner:origLink>http://darrell.mozingo.net/2008/06/30/automatically-run-your-unit-tests-during-compilation/</feedburner:origLink></item>
		<item>
		<title>KISS Is Hard</title>
		<link>http://feeds.mozingo.net/~r/TallerCode/~3/314591166/</link>
		<comments>http://darrell.mozingo.net/2008/06/18/kiss-is-hard/#comments</comments>
		<pubDate>Wed, 18 Jun 2008 12:35:35 +0000</pubDate>
		<dc:creator>Darrell Mozingo</dc:creator>
		
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">http://darrell.mozingo.net/?p=13</guid>
		<description><![CDATA[No, I&#8217;m not referring to the band, but the KISS principle (Keep It Simple, Stupid), and its close cousin, the idea of YAGNI (You Ain&#8217;t Gonna Need It).
They&#8217;re hard. Sure, they might seem easy at first glance, but they are both deceptively hard. This is especially true if you have any sort of background in [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignright" style="float: right;" title="KISS Logo" src="http://darrell.mozingo.net/wp-content/uploads/2008/06/kisslogo.png" alt="KISS Logo" />No, I&#8217;m not referring to <a href="http://en.wikipedia.org/wiki/Kiss_(band)">the band</a>, but <a href="http://en.wikipedia.org/wiki/KISS_principle">the KISS principle</a> (Keep It Simple, Stupid), and its close cousin, the idea of <a href="http://en.wikipedia.org/wiki/You_Ain%27t_Gonna_Need_It">YAGNI</a> (You Ain&#8217;t Gonna Need It).</p>
<p>They&#8217;re hard. Sure, they might seem easy at first glance, but they are both deceptively hard. This is especially true if you have any sort of background in your problem domain, and let&#8217;s face it, most of us do if we&#8217;re writing the usual problem tracking or invoice tracking applications. You know what I&#8217;m talking about: you start with an empty solution in front of you, tasked with creating your companies next, say, customer management system, and you start walking through the new application in your mind.</p>
<p>&#8220;Well,&#8221; you say to yourself, &#8220;I&#8217;m going to need a Customer object, a customer repository to store the object, a Job object, maybe an invoice object, tables and repositories for each of those, and I&#8217;m sure they&#8217;re going to ask for filtering next, so I might as well save myself the time and throw in a few specification and filtering classes.&#8221; This process goes on for a while and before you know if you&#8217;ve pumped out a few dozen classes and added all sorts of neat functionality.</p>
<p>Odds are, though, some, if not most, of those classes will end up either going unused or be <i>heavily</i> modified before the features are finished. Hence the above two principles (or ideas or whatever you want to call them). Wait until the last <strong>reasonable</strong> moment to add additional complexity to your application, but do so with a bit of judgment. Sometimes you simply know you&#8217;re going to need something, like a database back-end, so don&#8217;t start with text files just for the sake of keeping it simple. For the vast majority of decisions, though, you should use the simplest implementation until you find justifiable evidence that proves you need something more complex.</p>
<p>KISS and YAGNI go hand-in-hand with test driven development. Write your test, then write the simplest code you can to make the test pass. The code can always be refactored later to extract classes, interfaces, patterns, et cetera. I understand that your training as a developer is hard to resist - that urge to create things you&#8217;re pretty sure you&#8217;ll need while you&#8217;re working in a particular area. Resist it.</p>
<p>I&#8217;m starting on a new project at work, and it&#8217;s a particularly large project at that. It lends itself incredibly well to TDD, and so far the YAGNI ideal and TDD practice has proven themselves very versatile and helpful. As we&#8217;re unsure on how to split up the work load this early in the project, we&#8217;re working together (3 developers) on a machine with a projector. We&#8217;re <strong>constantly</strong> reminding each other not to over complicate things and toss in hooks and features we might someday need. Trust me, I literally mean almost every feature we add we&#8217;re reminding each other to go with the simpler implementation, because it really is that hard to overcome. We&#8217;re trying to stick to today, not tomorrow, by making it simple, making it fast, and making it easy to understand. I think we&#8217;re doing a great job of it so far.</p>
<p>We&#8217;re also well assured that the dozens and dozens of unit tests we have, along with the multitude of user generated acceptance/integration tests, will give us the safety net we need to refactor and introduce new features as we move forward. I, for one, am quite looking forward to what comes next.</p>
]]></content:encoded>
			<wfw:commentRss>http://darrell.mozingo.net/2008/06/18/kiss-is-hard/feed/</wfw:commentRss>
		<feedburner:origLink>http://darrell.mozingo.net/2008/06/18/kiss-is-hard/</feedburner:origLink></item>
		<item>
		<title>MbUnit’s ThreadedRepeat Attribute</title>
		<link>http://feeds.mozingo.net/~r/TallerCode/~3/301438847/</link>
		<comments>http://darrell.mozingo.net/2008/05/30/mbunits-threadedrepeat-attribute/#comments</comments>
		<pubDate>Fri, 30 May 2008 18:49:55 +0000</pubDate>
		<dc:creator>Darrell Mozingo</dc:creator>
		
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://darrell.mozingo.net/?p=11</guid>
		<description><![CDATA[I ran into some old code in a utility library the other day that would open an XML file on a network share, read a few settings, and close it. This particular piece of code is called quite often in many situations, and often in larger loops, as the calling developer just sees a string [...]]]></description>
			<content:encoded><![CDATA[<p>I ran into some old code in a utility library the other day that would open an XML file on a network share, read a few settings, and close it. This particular piece of code is called quite often in many situations, and often in larger loops, as the calling developer just sees a string being returned and is oblivious to the fact that it&#8217;s pretty damn expensive to get that string.</p>
<p>So I figured I&#8217;d go ahead and implement some quick caching around this by storing the strings in generic static Dictionary, especially as the method itself was static. As I&#8217;m still trudging up the steep hill that is the learning curve of Test Driven Development (TDD), I thought I&#8217;d get a failing test in there first, then make it pass. An interface for <a href="http://msdn.microsoft.com/en-us/library/aa973811.aspx">dependency injection</a> and a <a href="http://weblogs.asp.net/stephenwalther/archive/2008/03/22/tdd-introduction-to-rhino-mocks.aspx">mock</a> or two later and it works. All is good and well in the world.</p>
<p>Unfortunately, it didn&#8217;t take long for me to realize there were some serious threading issues going on. Whoops. So I started writing up a unit test to fail on the bug before I fixed it, and in the process of creating a bunch of worker threads to hit the method at the same time, I stumbled across a nifty feature in MbUnit: the <code>ThreadedRepeate</code> Attribute. Behold, a fake example:</p>
<pre name="code" class="c#:nocontrols" cols="80" rows="10">
[Test]
[ThreadedRepeat(5)]
public void Should_handle_multithreaded_access()
{
	Assert.IsNotEmpty(MyClass.GetExpensiveString());
}
</pre>
<p>Just like the normal <code>[Repeat(5)]</code> attribute, which would simply call the test 5 consecutive times back to back, the <code>[ThreadedRepeat(5)]</code> attribute will call the test 5 times <strong>in parallel</strong>, firing off a separate thread for each one.</p>
<p>Pretty freakin&#8217; nifty if you ask me, and a whole lot easier than having to write your own code to spin up a bunch of worker threads.</p>
]]></content:encoded>
			<wfw:commentRss>http://darrell.mozingo.net/2008/05/30/mbunits-threadedrepeat-attribute/feed/</wfw:commentRss>
		<feedburner:origLink>http://darrell.mozingo.net/2008/05/30/mbunits-threadedrepeat-attribute/</feedburner:origLink></item>
		<item>
		<title>C# 3.0 Automatic Property Gotcha</title>
		<link>http://feeds.mozingo.net/~r/TallerCode/~3/298774777/</link>
		<comments>http://darrell.mozingo.net/2008/05/26/c-30-automatic-property-gotcha/#comments</comments>
		<pubDate>Tue, 27 May 2008 02:14:10 +0000</pubDate>
		<dc:creator>Darrell Mozingo</dc:creator>
		
		<category><![CDATA[Quickie]]></category>

		<guid isPermaLink="false">http://darrell.mozingo.net/?p=10</guid>
		<description><![CDATA[One of the neat new features of C# 3.0 is the automatic properties syntax. It&#8217;s basically a quicker and simpler way to declare properties, as you don&#8217;t need to create a private backing object for each one as you&#8217;ve always had to. Here&#8217;s an example:

public class Person
{
	// Original way:
	private string _name;
	public string Name
	{
		get { return [...]]]></description>
			<content:encoded><![CDATA[<p>One of the neat new features of C# 3.0 is the <a href="http://weblogs.asp.net/scottgu/archive/2007/03/08/new-c-orcas-language-features-automatic-properties-object-initializers-and-collection-initializers.aspx">automatic properties</a> syntax. It&#8217;s basically a quicker and simpler way to declare properties, as you don&#8217;t need to create a private backing object for each one as you&#8217;ve always had to. Here&#8217;s an example:</p>
<pre name="code" class="c#:nocontrols" cols="80" rows="10">
public class Person
{
	// Original way:
	private string _name;
	public string Name
	{
		get { return _name; }
		set { _name = value; }
	}

	// New, automatic property, way:
	public int Age { get; set; }
}
</pre>
<p>Using the second example, the compiler will basically create a private <code>Age</code> member in the background and use in the generated getter/setter of the new property. If the it&#8217;s a numeric type, as <code>Age</code> is, it will default to 0. If it&#8217;s a reference type, such as another class or a Nullable type (i.e. <code>int?</code>), it&#8217;ll default to null.</p>
<p>Now for the semi-gotcha: strings are reference types, so <strong>they&#8217;ll default to null</strong>. This may not be a problem in your situation, but I personally like to default all of my string to <code>string.Empty</code> (unless the situation calls for a null, which I find isn&#8217;t very often). I just don&#8217;t like the hassle of dealing with null strings, though the <code>string.IsNullOrEmpty()</code> method helps mitigate that.</p>
<p>So there ya go. Take it for what it&#8217;s worth - something to keep in mind when using the new automatic property feature.</p>
]]></content:encoded>
			<wfw:commentRss>http://darrell.mozingo.net/2008/05/26/c-30-automatic-property-gotcha/feed/</wfw:commentRss>
		<feedburner:origLink>http://darrell.mozingo.net/2008/05/26/c-30-automatic-property-gotcha/</feedburner:origLink></item>
		<item>
		<title>Cleveland Day of .NET Review</title>
		<link>http://feeds.mozingo.net/~r/TallerCode/~3/294430521/</link>
		<comments>http://darrell.mozingo.net/2008/05/20/cleveland-day-of-net-review/#comments</comments>
		<pubDate>Tue, 20 May 2008 17:37:04 +0000</pubDate>
		<dc:creator>Darrell Mozingo</dc:creator>
		
		<category><![CDATA[Reviews]]></category>

		<guid isPermaLink="false">http://darrell.mozingo.net/?p=12</guid>
		<description><![CDATA[I attended the first annual Cleveland Day of .NET this past Saturday, the 17th. Other than a few Microsoft launch-type events, I&#8217;ve never attended an actual community get together like this before, so it was a new experience for me.
Do I think it was worth it, in terms of the time (7 AM to 6:30 [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignright" style="float: right;" src="http://darrell.mozingo.net/wp-content/uploads/2008/05/CDoDN.png" alt="Cleveland Day of .NET" width="147" height="137" />I attended the first annual Cleveland Day of .NET this past Saturday, the 17th. Other than a few Microsoft launch-type events, I&#8217;ve never attended an actual community get together like this before, so it was a new experience for me.</p>
<p>Do I think it was worth it, in terms of the time (7 AM to 6:30 PM on a Saturday with decent weather) and money (gas for a 100 mile round trip and lunch) invested? Well, lets take a look at each of the six presentations I attended and then at an overview of the whole event:</p>
<ol>
<li><strong>Why Ruby?</strong> - <a href="http://www.objo.com/">Joe O&#8217;Brien</a>
<ul>
<li>Joe started off by saying this wouldn&#8217;t be a talk about specifics in Ruby or a 100 level intro, and he delivered on that. Instead, he focused on some neat features of Ruby that&#8217;d make a seasoned developer want to dabble with it and potentially jump ship. I&#8217;ve seen a bit of Ruby glancing through blogs and articles, and even wrote one or two <em>very</em> basic learning applications in it, so I was glad he skipped the syntax basics and instead focused on things such as catching missing methods and then relating that to O/RM and enterprise development uses.Ultimately, I thought this was a great talk. Joe was quite the funny presenter, kept me engaged the whole time, recovered very gracefully from a few presentation hiccups, showed some neat examples, and renewed my appetite for Ruby. It was a nice presentation to start out the day, for sure.</li>
</ul>
</li>
<li><strong>Introduction to Test Driven Development with the ASP.NET MVC Framework</strong> - <a href="http://netcave.org/">Alan Stevens</a>
<ul>
<li>Alan began with an intro to the ASP.NET MVC Framework and followed up with a few live coded unit tests. While I liked his presentation style (his excitement for this stuff was contagious), I wasn&#8217;t too impressed with the content. It was very solid information, but I had some higher expectations going in, and he only got around to doing basic unit tests to check the rendered view and such things. Nothing really new for me there, unfortunately, but it was still nice to hear the MVC architectural pattern explained from a different point of view.</li>
</ul>
</li>
<li><strong>Software Ninjitsu: Designing for Change</strong> - <a href="http://kohari.org/">Nate Kohari</a>
<ul>
<li>Focusing on the foundation of object design - cohesion and coupling - then moving onto the basics of Inversion of Control (IoC) using his Dependency Injection (DI) framework, <a href="http://ninject.org/">Ninject</a> (which I&#8217;ve looked at before and is actually pretty neat), Nate delivered an awesome presentation. Admittedly his first large one, he handled a failing projector halfway through the presentation with ease, and the room was packed with standing room only. He touched briefly on a few other aspects of his framework such as Aspect Oriented Programming (AOP), but he stuck to the basics of IoC very well and presented them, at least I thought, in a very logical fashion. His gratuitous use of ninja references was actually pretty funny (although you couldn&#8217;t expect anything less with a session title like that) and was a nice change of pace.The <em>only</em> thing I would have liked to see was some more live code. He stuck to Power Point (or whatever the Mac equivalent he was using was) pretty good, though a bit of Visual Studio and bigger examples might have helped a bit, I think. Overall it was a great presentation though.</li>
</ul>
</li>
<li><strong>Ouch, that hurt! Lessons Learned from an Agile Project</strong> - <a href="http://michaeleatonconsulting.com/blog/">Michael Eaton</a>
<ul>
<li>I was looking forward to this session the most. My team is currently shifting into a RUP/Agile methodology (and actually had a nice 2 hour discussion on this the Friday before this event), so I asked Michael if I could tape the talk with the hopes of showing it to the rest of my team when I got back to work. It was a good talk, reminding everyone about the major pain points in project management: communication, buy-in, estimating, etc. Some were client specific while some were more common. It spurred some interesting discussion from the crowd though, and Michael&#8217;s slide deck was a pretty funny addition. Also, while I could also see where he was coming from in the talk, the fact that he concentrated on one single job as an example, out of the many I&#8217;m sure he&#8217;s worked on, made parts of the presentation seem like a rant instead being informational.Unfortunately, in the end the presentation wasn&#8217;t exactly what I&#8217;d thought it&#8217;d be. While we did hit a lot of common pain points, to me they weren&#8217;t really related to, or caused by, any particular Agile methodology. They were just general issues that most everyone - including my team - has dealt with in the past. Helpful to be sure, but I was looking for issues relating specifically to a flavor of Agile, such as TDD acceptance, short iteration deliverables, pair-programming acceptance, stand-up meeting issues, planning problems, etc.</li>
</ul>
</li>
<li><strong>Data Access with NHibernate</strong> - <a href="http://geekswithblogs.net/ignu/Default.aspx">Len Smith</a>
<ul>
<li>Len started off with a quick intro to O/RMs in general and why you&#8217;d want to use one, then jumped into talking about various aspects of NHibernate interlaced with live code examples. His examples were pretty decent, using unit tests as quick code harnesses to show off various features like batch queries, lazy loading, SQL query inspection, etc. Pretty standard stuff, and I thought he did a good job explaining it, along with answering a few questions that popped up through the session such as the ability to use NHibernate along side current data access code during a transition period (to which Len just suggested rewriting your data layer). Like Nate Kohari&#8217;s talk, he used a lot of pirate and ninja references which I thought was pretty cool.</li>
</ul>
</li>
<li><strong>Intro to the IronPython Flying Circus</strong> - <a href="http://www.codinggeekette.com">Sarah Dutkiewicz</a>
<ul>
<li>Sarah began by making a case for Python then jumping right into some examples of IronPython, using gratuitous amounts of Monty Python references of course (Ni!). She showed a few basic features of Python and IronPython using the interactive command line tool, including how to use those little animated people from the Windows XP first install wizard. She did a really good job presenting a high-level overview of the features, I thought.</li>
</ul>
</li>
</ol>
<p>There&#8217;s a few other presentations that sounded really interesting and I would have loved to see, and in hindsight I should have floated between some of these sessions to get in a little more more material. I&#8217;ll have to keep that in mind for next time.</p>
<ol>
<li><strong>Silverlight in ASP.NET </strong>- <a href="http://tocode.blogspot.com/">John Stockton</a></li>
<li><strong>IronRuby, the DLR and Silverlight </strong>- <a href="http://adanacp.spaces.live.com/">Carey Payette</a></li>
<li><strong>A Look at F# </strong>- <a href="http://www.pandamonial.com/">Amanda Laucher</a></li>
</ol>
<p>Now, as for the event as a whole I&#8217;d have to give it a thumbs up. Everyone got a free, decent quality, tee-shirt upon sign-in, which was neat (standard logo + sponsors white tee). They were giving away books in nearly all the sessions for various reasons, and also gave out licenses to some nice software and an XBox 360 at the end, but I didn&#8217;t win anything <img src='http://darrell.mozingo.net/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> </p>
<p>I met a few people there from the Akron area, though I wished I would have networked a bit more. As Michael Eaton put in his review, the small hallways and constant moving of hotel staff made it tough to talk to anyone between sessions.</p>
<p>Attending this event has also peaked my interested in presenting on a topic at some point, perhaps starting with one to my co-workers (though I sort of did one on Linq To SQL a while ago). I&#8217;d love to have something to present, and the ability to do it, at a future event like this.</p>
<p>Overall I thought the event was well worth the time and money invested (it being free and getting free swag sure helped). I met some nice people and picked up a lot of new information, and I&#8217;m looking forward to attending next year.</p>
<p>Too bad Cleveland is the nearest .NET user group, and they usually start at like 6 PM, as I&#8217;d love to attend a few of those but scheduling is usually too tuff. That&#8217;s why I&#8217;d like to get the ball rolling on the <a href="http://cantonalt.net">CantonALT.NET</a> user group, so we can spark some local discussion and interest.</p>
]]></content:encoded>
			<wfw:commentRss>http://darrell.mozingo.net/2008/05/20/cleveland-day-of-net-review/feed/</wfw:commentRss>
		<feedburner:origLink>http://darrell.mozingo.net/2008/05/20/cleveland-day-of-net-review/</feedburner:origLink></item>
		<item>
		<title>The Strategy Pattern and Filtering</title>
		<link>http://feeds.mozingo.net/~r/TallerCode/~3/291873415/</link>
		<comments>http://darrell.mozingo.net/2008/05/16/the-strategy-pattern-and-filtering/#comments</comments>
		<pubDate>Fri, 16 May 2008 20:16:35 +0000</pubDate>
		<dc:creator>Darrell Mozingo</dc:creator>
		
		<category><![CDATA[Design Patterns]]></category>

		<guid isPermaLink="false">http://darrell.mozingo.net/?p=8</guid>
		<description><![CDATA[The strategy pattern is a way to inject algorithms into a chunk of code, or as I like to think of it, basically a way to refactor out multiple lines of code and pass them into a method. Let&#8217;s look at an example.
Say you have a method with some hard coded strings:

public string WrapWithSingleQuote(string text)
{
	return [...]]]></description>
			<content:encoded><![CDATA[<p>The strategy pattern is a way to inject algorithms into a chunk of code, or as I like to think of it, basically a way to refactor out multiple lines of code and pass them into a method. Let&#8217;s look at an example.</p>
<p>Say you have a method with some hard coded strings:</p>
<pre name="code" class="c#:nocontrols" cols="80" rows="10">
public string WrapWithSingleQuote(string text)
{
	return "'" + text + "'";
}
</pre>
<p>Now in your next iteration you&#8217;re asked to wrap any needed text in double quotes and/or parenthesis. Being the awesome developer that you are, you generalize the method like so:</p>
<pre name="code" class="c#:nocontrols" cols="80" rows="10">
public string WrapWithString(string text, string wrapper)
{
	return wrapper + text + wrapper;
}
</pre>
<p>See that? The <code>wrapper</code> parameter that allowed you to pass whatever you want to wrap the text in? That&#8217;s a <strong>simplistic and primitive</strong> example of the strategy pattern, but an example nonetheless. Now the method allows you to wrap the given text in whatever characters your heart desires.</p>
<p>Now for a bit more robust and real world example of the pattern. Let&#8217;s consider the .NET WinForm&#8217;s TextBox control. This control has auto-complete functionality built into it to, able to suggest completed entries based off the currently entered text from a variety of sources: file system, URL&#8217;s, a custom source, and more.</p>
<p>A few requirements come in stating that the users want auto-completion for the company text box in their mythical application, so you whip up the following user control:</p>
<pre name="code" class="c#:nocontrols" cols="80" rows="10">
public partial class CompanyFindTextBox : TextBox
{
	public CompanyFindTextBox()
	{
		InitializeComponent();

		this.AutoCompleteMode = AutoCompleteMode.Suggest;
		this.AutoCompleteSource = AutoCompleteSource.CustomSource;
	}

	public CompanyFindTextBox(IContainer container)
		: this()
	{
		container.Add(this);
	}

	protected override void OnKeyUp(KeyEventArgs e)
	{
		HandleAutoComplete(this.Text.Trim());
		base.OnKeyUp(e);
	}

	private void HandleAutoComplete(string searchText)
	{
		if(searchText != string.Empty)
		{
			using(DatabaseDataContext db = new DatabaseDataContext())
			{
				var matchingCompanies =
					from c in db.Companies
					where c.Name.ToUpper().StartsWith(searchText)
					orderby c.Name
					select c.Name;

				this.AutoCompleteCustomSource.AddRange(matchingCompanies.ToArray());
			}
		}
	}
}
</pre>
<p>Now, of course, the users want the same functionality on their job, candidate, contractor, and who knows what other text boxes. Looks like a refactoring is in order. Ah, but this time there isn&#8217;t a simple string to extract as a parameter to fix the problem! You need to generalize your LINQ statement, but each text box type is searching on different databases, fields, etc. </p>
<p>This where the power of the strategy pattern comes in. With it, you can tell the control/method how to go about executing a certain algorithm. Specifically, in C# we usually use delegates (which are nothing more than methods passed into other methods as parameters - or function points from lower level languages). Since C# 3.0 introduced lambdas (simply more concise ways to declare delegates), let&#8217;s go ahead and use those. Here&#8217;s a more generalized user control which uses the strategy pattern to pull out the specific database accessing code:</p>
<pre name="code" class="c#:nocontrols" cols="80" rows="10">
public partial class EntityFindTextBox : TextBox
{
	public Func<string, string[]> AutoCompleteStrategy { get; set; }

	public EntityFindTextBox()
	{
		InitializeComponent();

		this.AutoCompleteMode = AutoCompleteMode.Suggest;
		this.AutoCompleteSource = AutoCompleteSource.CustomSource;
	}

	public EntityFindTextBox(IContainer container)
		: this()
	{
		container.Add(this);
	}

	protected override void OnKeyUp(KeyEventArgs e)
	{
		HandleAutoComplete(this.Text.Trim());
		base.OnKeyUp(e);
	}

	private void HandleAutoComplete(string searchText)
	{
		if(AutoCompleteStrategy != null &#038;& searchText != string.Empty)
		{
			this.AutoCompleteCustomSource.AddRange(AutoCompleteStrategy(searchText));
		}
	}
}
</pre>
<p>Notice how this implementation has a function property named <code>AutoCompleteStrategy</code>. This says we&#8217;re looking for a method that takes in a string and returns an array of strings. Now in the <code>HandleAutoComplete</code> method, we make sure this isn&#8217;t null and call it with the text box&#8217;s contents. This abstracts out the actual database searching algorithm so the new user control can be used with any type of entity the system needs, be it companies, jobs, contractors, etc. That&#8217;s the strategy pattern in all its glory.</p>
<p>After dropping the new control on a form, you might set it up for a company like so:</p>
<pre name="code" class="c#:nocontrols" cols="80" rows="10">
txtCompanies.AutoCompleteStrategy = (searchTerm =>
	{
		using(DatabaseDataContext db = new DatabaseDataContext())
		{
			var matchingCompanies =
				from c in db.Companies
				where c.Name.ToUpper().StartsWith(searchText)
				orderby c.Name
				select c.Name;

			return matchingCompanies.ToArray();
		}
	});
</pre>
<p>Now we&#8217;re setting the <code>AutoCompleteStrategy</code> property to a new lambda expression (think quick method declaration) that&#8217;s accepting a string parameter named <code>searchTerm</code> and using it in the same LINQ query from before, ultimately returning an array of company names which contain whatever was passed in. We could do this for a job text box just as easily, simply swapping out the LINQ statement for a new one (or even XML file searching, a web service call, whatever).</p>
<p>Simple enough, right?</p>
]]></content:encoded>
			<wfw:commentRss>http://darrell.mozingo.net/2008/05/16/the-strategy-pattern-and-filtering/feed/</wfw:commentRss>
		<feedburner:origLink>http://darrell.mozingo.net/2008/05/16/the-strategy-pattern-and-filtering/</feedburner:origLink></item>
		<item>
		<title>Loading a DTO from LINQ To SQL</title>
		<link>http://feeds.mozingo.net/~r/TallerCode/~3/291873416/</link>
		<comments>http://darrell.mozingo.net/2008/05/09/loading-a-dto-from-linq-to-sql/#comments</comments>
		<pubDate>Fri, 09 May 2008 20:56:30 +0000</pubDate>
		<dc:creator>Darrell Mozingo</dc:creator>
		
		<category><![CDATA[Design Patterns]]></category>

		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://darrell.mozingo.net/?p=7</guid>
		<description><![CDATA[The background
A Data Transfer Object (DTO) is a plain old CLR object (POCO) mainly used to pass data between tiers and remote calls. They&#8217;re basically classes with getters, setters, and perhaps a constructor or two, but no methods. They&#8217;re dumb objects that simply hold data.
So why would you use these? A few reasons:

They flatten your [...]]]></description>
			<content:encoded><![CDATA[<h2>The background</h2>
<p>A <strong>D</strong>ata <strong>T</strong>ransfer <strong>O</strong>bject (DTO) is a plain old CLR object (POCO) mainly used to pass data between tiers and remote calls. They&#8217;re basically classes with getters, setters, and perhaps a constructor or two, but <em>no</em> methods. They&#8217;re dumb objects that simply hold data.</p>
<p>So why would you use these? A few reasons:</p>
<ol>
<li>They flatten your data. DTO&#8217;s can contain information from a multitude of sources (database, XML, web service, etc) all neatly packaged together, including any large hierarchies of data from your relational (SQL) store.</li>
<li>They more easily allow parameters to be passed into and out of methods, especially expensive ones like web services. You&#8217;re not forced to break a web service&#8217;s signature if you need to add/remove parameters if you pass in a DTO. The DTO can change and clients aren&#8217;t forced to immediately update. They also help keep method signatures nice and tidy.</li>
<li>They help decouple your layers by remaining technology and location agnostic. If your relational data moves around, you simply have to modify your data layer (or your business layer if you&#8217;re passing DTO&#8217;s back for presentation reasons) to get the needed information. The consuming layer won&#8217;t care that the data is coming from somewhere else, they&#8217;re just looking at the DTO&#8217;s copy.</li>
</ol>
<h2>The setup</h2>
<p>Let&#8217;s look at a simple scenario. We&#8217;re loading a business object and calling out to our data layer for the information, which we&#8217;ll get from SQL using LINQ to SQL. The following DTO will be passed back:</p>
<pre name="code" class="c#:nocontrols" cols="80" rows="10">
public class PersonDTO
{
	public string FirstName { get; set; }
	public string LastName { get; set; }
	public int Age { get; set; }
	public decimal HourlyWage { get; set; }
}
</pre>
<h2>The code</h2>
<p>Let&#8217;s look at the GetPerson method from the data layer, which uses LINQ to SQL to retrieve the needed information from SQL:</p>
<pre name="code" class="c#:nocontrols" cols="80" rows="10">
public PersonDTO GetPerson(int personID)
{
	using(DatabaseDataContext db = new DatabaseDataContext())
	{
		return (from p in db.Peoples
			    join pw in db.PeopleWages on p.PersonID equals pw.PersonID
			    where p.PersonID == personID
			    select new PersonDTO
			    {
					FirstName = p.FirstName,
					LastName = p.LastName,
					Age = p.Age,
					HourlyWage = pw.HourlyWage
			    }
			   ).SingleOrDefault();
	}
}
</pre>
<p>The key bit is the <code>select new PersonDTO</code> and its four accompanying lines. It might look a bit odd, but it&#8217;s the new <a href="http://weblogs.asp.net/scottgu/archive/2007/03/08/new-c-orcas-language-features-automatic-properties-object-initializers-and-collection-initializers.aspx">object initializer</a> syntax added to C# 3.0. The compiler is basically creating a constructor in the background, taking in the specified parameters, and setting their respective property values.</p>
<p>This keeps your simple select methods such as this visually clean. No need to return a LINQ object and set each property in a separate call. OK, not a huge positive, but hey, it&#8217;s the small things that count. I personally love clean, slick, code.</p>
<p>Also note the <code>SingleOrDefault()</code> call at the end, which will return a single object from the LINQ statement (which in this case is of type <code>PersonDTO</code>) or a default value for that object if one isn&#8217;t found (and since we&#8217;re selecting a reference type, it&#8217;d return <code>null</code>). <code>SingleOrDefault()</code> will throw an exception if more than one record is returned from SQL, but since we&#8217;re looking for a primary key here, it shouldn&#8217;t be a problem.</p>
<p>As a side note, one of the neat features of Visual Studio 2008 is the IntelliSense&#8217;s ability to filter the already assigned properties within the object initializer portion of the LINQ statement. For instance, notice how it&#8217;s hiding the <code>FirstName</code> property in the pop-up since I assigned it in the line above:</p>
<p><img src="/wp-content/uploads/2008/05/dto-linq-to-sql-1.png" alt="IntelliSense filtering the available properites" /></p>
<p>To wrap up, here&#8217;s the <code>CreatePerson</code> method, on the Person object in the business layer, that would consume the above <code>GetPerson</code> method:</p>
<pre name="code" class="c#:nocontrols" cols="80" rows="10">
public Person CreatePerson(int personID)
{
	using(PersonDTO personDTO = DataLayer.GetPerson(personID))
	{
		return new Person
		{
			FirstName = personDTO.FirstName,
			LastName = personDTO.LastName,
			Age = personDTO.Age,
			HourlyWage = personDTO.HourlyWage
		};
	}
}
</pre>
<p>Notice how it too is making use of the new object initializer feature.</p>
]]></content:encoded>
			<wfw:commentRss>http://darrell.mozingo.net/2008/05/09/loading-a-dto-from-linq-to-sql/feed/</wfw:commentRss>
		<feedburner:origLink>http://darrell.mozingo.net/2008/05/09/loading-a-dto-from-linq-to-sql/</feedburner:origLink></item>
		<item>
		<title>Introduction</title>
		<link>http://feeds.mozingo.net/~r/TallerCode/~3/291873417/</link>
		<comments>http://darrell.mozingo.net/2008/04/16/introduction/#comments</comments>
		<pubDate>Wed, 16 Apr 2008 23:52:11 +0000</pubDate>
		<dc:creator>Darrell Mozingo</dc:creator>
		
		<category><![CDATA[Misc.]]></category>

		<guid isPermaLink="false">http://darrell.mozingo.net/?p=5</guid>
		<description><![CDATA[So I&#8217;ve finally done it: a development blog. This sure was a long time in the making.
So what&#8217;s up with the title? &#8220;Taller Code&#8221;? Well, it derives from two sources:

I&#8217;m on a personal journey of self betterment (relating to software development anyway). I want my code to get bigger, better, and &#8220;taller&#8221; in the metaphorical [...]]]></description>
			<content:encoded><![CDATA[<p>So I&#8217;ve finally done it: a development blog. This sure was a long time in the making.</p>
<p>So what&#8217;s up with the title? &#8220;Taller Code&#8221;? Well, it derives from two sources:</p>
<ol>
<li>I&#8217;m on a personal journey of self betterment (relating to software development anyway). I want my code to get bigger, better, and &#8220;taller&#8221; in the metaphorical sense, and I want to drag as many of my peers as I can along with me.</li>
<li>I&#8217;m a bit over 6&#8242;4&#8243;, so some would say I&#8217;m pretty tall myself.</li>
</ol>
<p>Retarded? Perhaps. Cheesy? Sure. The result of picking a name first and trying to think up an explanation for it afterwards? Definitely.</p>
<p>It works though, and I&#8217;m hoping it sets a tone for my future posts and gives me a bit of a goal to keep in mind while working on them.</p>
]]></content:encoded>
			<wfw:commentRss>http://darrell.mozingo.net/2008/04/16/introduction/feed/</wfw:commentRss>
		<feedburner:origLink>http://darrell.mozingo.net/2008/04/16/introduction/</feedburner:origLink></item>
	</channel>
</rss><!-- Dynamic Page Served (once) in 5.755 seconds --><!-- Cached page served by WP-Cache -->
