<?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>Whatever Blows Your Hair Back</title>
	<atom:link href="http://wilbloodworth.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://wilbloodworth.com</link>
	<description>Wil Bloodworth&#039;s Blog</description>
	<lastBuildDate>Thu, 12 Jan 2012 20:51:42 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<item>
		<title>Async CTP &#8211; Be Careful With Exceptions!</title>
		<link>http://wilbloodworth.com/2011/08/10/async-ctp-be-careful-with-exceptions/</link>
		<comments>http://wilbloodworth.com/2011/08/10/async-ctp-be-careful-with-exceptions/#comments</comments>
		<pubDate>Thu, 11 Aug 2011 04:38:33 +0000</pubDate>
		<dc:creator>Wil</dc:creator>
				<category><![CDATA[Asynchrony]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[async]]></category>

		<guid isPermaLink="false">http://wilbloodworth.com/?p=389</guid>
		<description><![CDATA[I&#8217;m certainly no Bill Wagner, Jon Skeet or any of the other extremely intelligent and talented individuals who know their way around the new C# and VB asynchronous &#8220;stuff&#8221; coming soon from Microsoft. However, why can&#8217;t I throw my tattered and torn hat in the ring every now and then right?! While preparing code for [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m certainly no <a href="http://billwagner.cloudapp.net/Home/Category/async">Bill Wagner</a>, <a href="http://msmvps.com/blogs/jon_skeet">Jon Skeet</a> or any of the other extremely intelligent and talented individuals who know their way around the new C# and VB asynchronous &#8220;stuff&#8221; coming soon from Microsoft.  However, why can&#8217;t I throw my tattered and torn hat in the ring every now and then right?!</p>
<p>While preparing code for my talk at the upcoming <a href="http://dallastechfest.com/">Dallas TechFest 2011</a>, and writing code samples to demonstrate how exceptions work with async and await, I ran across some nastiness that I really don&#8217;t think should be working, or in this case&#8230; breaking, the way it is in the refresh of the Async CTP.  Since I could not find any mention of this issue on any website or forum (I&#8217;m not saying they don&#8217;t exist), I am going to show you it here.</p>
<p>Without any further ado, exceptions&#8230; inside an async method.  Exceptions are supposed to propagate to the caller who is awaiting the completion of an async call. But&#8230; take this code for example:</p>
<pre class="brush: csharp">
public void Run()
{
	try
	{
		MyVoidAsyncMethod(null);

		Console.WriteLine(&quot;Press a key...&quot;);
		Console.ReadLine(); // &lt;--- BIG problem!
	}
	catch (Exception ex_)
	{
		Console.WriteLine(ex_.Message);
	}
	Console.WriteLine(&quot;You&#039;ll never see this!&quot;);
}

private async void MyVoidAsyncMethod(string betterNotBeNull)
{
	if (string.IsNullOrEmpty(betterNotBeNull))
		throw new ArgumentNullException(&quot;That&#039;s why we can&#039;t have nice things!&quot;);

	await TaskEx.Yield();
}
</pre>
<p>Here&#8217;s what you get if you execute it:</p>
<p><em><strong>Press a key&#8230;</p>
<p>Unhandled Exception: System.ArgumentNullException: Value cannot be null.<br />
Parameter name: That&#8217;s why we can&#8217;t have nice things!</p>
<p>Server stack trace:<br />
   at DallasTechFest_2011.DeleteMe.<MyVoidAsyncMethod>d__0.MoveNext() in C:\DTF2011\DallasTechFest2011_Async\02 Exception Demos\DeleteMe.cs:line 27</p>
<p>Exception rethrown at [0]:<br />
   at System.Runtime.CompilerServices.AsyncVoidMethodBuilder.<SetException>b__1(Object state)<br />
   at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)<br />
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)<br />
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()<br />
   at System.Threading.ThreadPoolWorkQueue.Dispatch()<br />
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()<br />
Press any key to continue . . .</strong><br />
</em></p>
<p>The UI thread is blocked by the Console.ReadLine() and that totally hoses up the entire system&#8230; and it crashes the application immediately.  This is an edge case and is definitely one of those, &#8220;Doctor, it hurts when I do this.  Well, don&#8217;t do that!&#8221; situations.  You probably shouldn&#8217;t be blocking the UI thread that called the async method anyway&#8230; so say&#8217;th the peanut gallery&#8230; and I agree.</p>
<p>However, it is inside a try/catch which &#8220;appears&#8221; to be completely ignored.  This all has to do with the way the compiler generates the code for an async method.  The first thing it is contractually obligated to do is to create an AsynVoidMethodBuilder object&#8230; and it does as you can see from the exception above.  But since this is an &#8216;async voic&#8217; method, it sort of freaks out&#8230; which I believe (ultimately) it shouldn&#8217;t.</p>
<p>Now, if you replace the async method with one that returns a Task<> like this:</p>
<pre class="brush: csharp">
private async Task&lt;int&gt; MyTaskAsyncMethod(string betterNotBeNull)
{
	if (string.IsNullOrEmpty(betterNotBeNull))
		throw new ArgumentNullException(&quot;That&#039;s why we can&#039;t have nice things!&quot;);

	await TaskEx.Yield();

	return 42;
}
</pre>
<p>Then&#8230; all you get for output is:</p>
<p><em>Press a key&#8230;</em></p>
<p>Moral?  Not sure&#8230; maybe it&#8217;s don&#8217;t block your UI?!  Maybe it&#8217;s just a hole that will be filled shortly by the C# compiler team before C# 5 ships.  It&#8217;s worth noting at least.  You&#8217;ve been warned!</p>
]]></content:encoded>
			<wfw:commentRss>http://wilbloodworth.com/2011/08/10/async-ctp-be-careful-with-exceptions/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Texas Hold &#8216;Em at FullTiltPoker.com</title>
		<link>http://wilbloodworth.com/2011/02/05/texas-hold-em-at-fulltiltpoker-com/</link>
		<comments>http://wilbloodworth.com/2011/02/05/texas-hold-em-at-fulltiltpoker-com/#comments</comments>
		<pubDate>Sat, 05 Feb 2011 20:39:35 +0000</pubDate>
		<dc:creator>Wil</dc:creator>
				<category><![CDATA[poker]]></category>
		<category><![CDATA[full-tilt]]></category>
		<category><![CDATA[online gaming]]></category>
		<category><![CDATA[texas hold 'em]]></category>

		<guid isPermaLink="false">http://wilbloodworth.com/?p=374</guid>
		<description><![CDATA[Yes, I know this is my development blog but there are a lot of .Net&#8217;ers out there who play poker; specifically, Texas Hold &#8216;Em. I play sporadically or on occasion online at Full Tilt Poker. It&#8217;s fun and, so far, it&#8217;s been a money-making adventure. Last night I was in a hand for a very [...]]]></description>
			<content:encoded><![CDATA[<p>Yes, I know this is my development blog but there are a lot of .Net&#8217;ers out there who play poker; specifically, Texas Hold &#8216;Em.  I play sporadically or on occasion online at <a href="http://fulltiltpoker.com">Full Tilt Poker</a>.  It&#8217;s fun and, so far, it&#8217;s been a money-making adventure.  Last night I was in a hand for a very short period of time and I was extremely glad that I got out of the hand when I did (pre-flop).  Click on this image to see what a tragic hand this was for a couple of people with great hands:  <a href="http://wilbloodworth.com/wp-content/uploads/2011/02/05/HandFromHell.jpg" rel="lightbox[374]"><img src="http://wilbloodworth.com/wp-content/uploads/2011/02/05/texasholdem.jpg"/></a></p>
<p>Ah, that&#8217;s just the way it goes sometimes!</p>
<p><!-- Begin W3Counter Tracking Code --><br />
<script type="text/javascript" src="http://www.w3counter.com/tracker.js"></script><br />
<script type="text/javascript">
w3counter(31137);
</script><br />
<noscript></p>
<div><a href="http://www.w3counter.com"><img src="http://www.w3counter.com/tracker.php?id=31137" style="border: 0" alt="W3Counter" /></a></div>
<p></noscript><br />
<!-- End W3Counter Tracking Code--></p>
]]></content:encoded>
			<wfw:commentRss>http://wilbloodworth.com/2011/02/05/texas-hold-em-at-fulltiltpoker-com/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Vyew.com &#8211; FREE Alternative to WebEx and GoToMeeting</title>
		<link>http://wilbloodworth.com/2011/02/04/vyew-com-free-alternative-to-webex-and-gotomeeting/</link>
		<comments>http://wilbloodworth.com/2011/02/04/vyew-com-free-alternative-to-webex-and-gotomeeting/#comments</comments>
		<pubDate>Fri, 04 Feb 2011 15:39:17 +0000</pubDate>
		<dc:creator>Wil</dc:creator>
				<category><![CDATA[Collaboration]]></category>
		<category><![CDATA[Productivity]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[colaboration]]></category>
		<category><![CDATA[gotomeeting]]></category>
		<category><![CDATA[vyew]]></category>
		<category><![CDATA[webex]]></category>

		<guid isPermaLink="false">http://wilbloodworth.com/?p=356</guid>
		<description><![CDATA[Vyew.com is a fantastic alternative to spending $50 a month or more on GoToMeeting (which requires a download) or WebEx. They Vyew interface is entirely web-based so there is no requirement of downloading any additional client software. It&#8217;s written with Adobe Flash and Java (as far as I can tell) and seems to be extremely [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://Vyew.com"><img src="http://wilbloodworth.com/wp-content/uploads/2011/02/Vyew.jpg" alt="Vyew.com" /></a><br />
<a href="http://Vyew.com">Vyew.com</a> is a fantastic alternative to spending $50 a month or more on <a href="http://gotomeeting.com">GoToMeeting</a> (which requires a download) or <a href="http://webex.com">WebEx</a>.  They Vyew interface is entirely web-based so there is no requirement of downloading any additional client software.  It&#8217;s written with Adobe Flash and Java (as far as I can tell) and seems to be extremely well laid out and responsive.  <em>&#8220;Vyew allows you to meet and share content in real-time or anytime. Upload images, files, documents and videos into a room. Users can access and contribute at anytime.&#8221;</em></p>
<p>Vyew is 100% free as long as you&#8217;re ok with advertisements and a somewhat limited account.  Still, the free account seems to have more power than the average Joe normally needs.  Should you find yourself not one of the average Joes, you can opt to pay for a &#8220;bigger&#8221; account with no advertising.  If you take this route, you&#8217;ll still pay 80% less than WebEx or GoToMeeting.</p>
<p>The only caveat is that it is not &#8220;live&#8221; like WebEx or GoToMeeting&#8230; meaning you can share but you can&#8217;t see the presenter&#8217;s screen in real-time fashion.  That may be a deal breaker for you.</p>
<p><a href="http://Vyew.com">Give them a shot and let me know what you think!</a><br />
<!-- Begin W3Counter Tracking Code --><br />
<script type="text/javascript" src="http://www.w3counter.com/tracker.js"></script><br />
<script type="text/javascript">
w3counter(31137);
</script><br />
<noscript></p>
<div><a href="http://www.w3counter.com"><img src="http://www.w3counter.com/tracker.php?id=31137" style="border: 0" alt="W3Counter" /></a></div>
<p></noscript><br />
<!-- End W3Counter Tracking Code--></p>
]]></content:encoded>
			<wfw:commentRss>http://wilbloodworth.com/2011/02/04/vyew-com-free-alternative-to-webex-and-gotomeeting/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Better Testing&#8230; Part II</title>
		<link>http://wilbloodworth.com/2011/02/04/better-testing-part-ii/</link>
		<comments>http://wilbloodworth.com/2011/02/04/better-testing-part-ii/#comments</comments>
		<pubDate>Fri, 04 Feb 2011 13:59:52 +0000</pubDate>
		<dc:creator>Wil</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Code Coverage]]></category>
		<category><![CDATA[Extension Methods]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[code coverage]]></category>
		<category><![CDATA[ncover]]></category>
		<category><![CDATA[nunit]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://wilbloodworth.com/?p=343</guid>
		<description><![CDATA[So you&#8217;ve dug in and started directly testing (using the extension methods I provided in Part I) your protected and private methods where, hopefuly, the vast majority of your business logic resides. In this post I want to show you how to invoke a method that is an overload on the same class. Using the [...]]]></description>
			<content:encoded><![CDATA[<p>So you&#8217;ve dug in and started directly testing (using the extension methods I provided in <a href="http://wilbloodworth.com/2011/02/03/better-testing-and-code-coverage-with-ncover/">Part I</a>) your protected and private methods where, hopefuly, the vast majority of your business logic resides.  In this post I want to show you how to invoke a method that is an overload on the same class.  Using the GetMethod method on Type will puke if more than one method with the same exact name exists on the type you&#8217;re attempting to call.  Here&#8217;s how to fix that problem:</p>
<pre class="brush: csharp">
	// Call the AddException method on the _importer object.
	// The 2nd parameter to &#039;Call&#039; is the parameter list to pass to AddException
	// The 3rd parameter to &#039;Call&#039; is the types of the parameters expected by the AddException method
	_importer.Call(&quot;AddException&quot;, new object[] { new Exception(&quot;blah&quot;) }, new [] { typeof(Exception) });
</pre>
<p>You can see that the parameter list is an object[] so the Type.GetMethod method has no way of differentiating between two methods with the same name solely by looking at the parameters passed in. You have to specifically tell it, &#8220;Hey, I want you to call the &#8216;AddException&#8217; method that expects an &#8216;Exception&#8217; parameter.</p>
<p>Some might say, why not just create a phat testing base class instead of creating these extension methods.  You could do that.  However, I personally feel that this is slightly cleaner and a bit more readable.  There are times when a testing base class comes in quite handy and I pretty much always use one&#8230; for a completely different reason though.</p>
<p>Let&#8217;s take a traditional look at how to write a test where you expect an exception to be thrown.</p>
<pre class="brush: csharp">
[Test, ExpectedException(typeof(ApplicationException))]
public void Demonstrate_NUnitWayOfExpectingExceptions()
{
	// This &#039;throw&#039; will cause the test to pass because this test is
	// decorated above with the &#039;ExpectedException attribute.
	throw new ApplicationException(exceptionMessage);
}
</pre>
<p>If you do it this way, there&#8217;s no (decent) way to look at the thrown exception or do anything beyond where the exception is thrown.  That&#8217;s not exactly &#8216;ideal&#8217; when more than one type of exception could be thrown or if you want to do multiple things in the same method after the exception is thrown.  Now let&#8217;s look at a slightly better way to do just that.</p>
<p>If you downloaded <a href="http://www.wilbloodworth.com/wp-content/uploads/2011/02/BetterTesting.zip">the source code in Part I</a>, you&#8217;ll find a class named TestingBase.</p>
<pre class="brush: csharp">
[Test]
public void Demonstrate_ExpectException()
{
	// ExpectException (on base class) is great when you expect an exception but
	// ... the ExpectedException attribute just doesn&#039;t give you enough flexibility
	string exMessage = ExpectException&lt;ApplicationException&gt;(() =&gt; { throw new ApplicationException(exceptionMessage); });
	Assert.IsNotNull(exMessage);
	Assert.AreEqual(exMessage, exceptionMessage);

	// We&#039;re also free to continue more testing and still be in the same &#039;state&#039;
	// Here we can write several lines of code &#039;inline&#039;... no problem.
	exMessage = ExpectException&lt;FileNotFoundException&gt;
		(() =&gt;{
				using (var reader = new StreamReader(&quot;this is not a valid file path&quot;))
					reader.ReadToEnd();
			});
	Assert.IsNotNull(exMessage);
	Assert.IsTrue(exMessage.Contains(&quot;Could not find file&quot;));
}
</pre>
<p>In the test above, we are calling a base class method called ExpectException which, as you can see, expects an exception of type ApplicationException to be thrown.  ExpectException takes an Action and will execute the action and swallow any thrown exceptions, validate an exception is actually thrown, and ensure that the thrown exception is of the specified type.  It also returns the message inside the exception so just in case you have more than one code branch that throws the same type of exception but has a different message&#8230; you&#8217;re able to validate that as well as is done in the code above.</p>
<p>Using the ExpectException method gives you more flexibility and to continue executing code in the test.  There are times when you may need to write a test that calls a method twice in order to have it throw an exception.  The ExtractId method in the Part I post has logic to ensure that the Person Id is only added once so that no two people can have the same Id.  That is an example of a case where you would need to call that method twice.  Now, ExtractId doesn&#8217;t throw an exception on the first call but it&#8217;s just an example and if it did, you could use ExpectException in that situation to make quick work of that test.</p>
<p>If you don&#8217;t want to bother with checking the returned exception string, you can use the other method on that base class called ExceptionWithMsg.  Here&#8217;s an example of how to use it:</p>
<pre class="brush: csharp">
// ExceptionWithMsg is &quot;implemented in terms of&quot; ExpectException... meaning it
// just calls ExpectException and then verifies that the exception message contains
// the textual fragment passed in.
ExceptionWithMsg&lt;FileNotFoundException&gt;
	(() =&gt;{
			using (var reader = new StreamReader(&quot;this is not a valid file path&quot;))
				reader.ReadToEnd();
		},
		&quot;Could not find file&quot;
	);
</pre>
<p>ExceptionWithMsg just calls ExpectException and tests the message for you&#8230; as you can see from the implementation:</p>
<pre class="brush: csharp">
protected void ExceptionWithMsg&lt;ExceptionType&gt;(Action action_, string exceptionMessageFragment_)
{
	Assert.IsTrue(ExpectException&lt;ExceptionType&gt;(action_).Contains(exceptionMessageFragment_));
}
</pre>
<p>Enjoy!<br />
<!-- Begin W3Counter Tracking Code --><br />
<script type="text/javascript" src="http://www.w3counter.com/tracker.js"></script><br />
<script type="text/javascript">
w3counter(31137);
</script><br />
<noscript></p>
<div><a href="http://www.w3counter.com"><img src="http://www.w3counter.com/tracker.php?id=31137" style="border: 0" alt="W3Counter" /></a></div>
<p></noscript><br />
<!-- End W3Counter Tracking Code--></p>
]]></content:encoded>
			<wfw:commentRss>http://wilbloodworth.com/2011/02/04/better-testing-part-ii/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Better Testing&#8230; and Code Coverage with NCover</title>
		<link>http://wilbloodworth.com/2011/02/03/better-testing-and-code-coverage-with-ncover/</link>
		<comments>http://wilbloodworth.com/2011/02/03/better-testing-and-code-coverage-with-ncover/#comments</comments>
		<pubDate>Fri, 04 Feb 2011 04:00:44 +0000</pubDate>
		<dc:creator>Wil</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Code Coverage]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[code coverage]]></category>
		<category><![CDATA[ncover]]></category>
		<category><![CDATA[nunit]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://wilbloodworth.com/?p=319</guid>
		<description><![CDATA[Project Managers are always looking for way to reduce subjectivity when it comes to code quality. They&#8217;re held to higher and higher standards with each passing day so it&#8217;s no surprise they are constantly coming to the team with questions related to software code &#8220;quality&#8221;. That word (quality) means a lot of things to a [...]]]></description>
			<content:encoded><![CDATA[<p>Project Managers are always looking for way to reduce subjectivity when it comes to code quality.  They&#8217;re held to higher and higher standards with each passing day so it&#8217;s no surprise they are constantly coming to the team with questions related to software code &#8220;quality&#8221;.  That word (quality) means a lot of things to a lot of people but to a product owner, it means keeping the maintenance costs as low as possible and reliability as high as possible.</p>
<p>That said, there are many ways to judge code quality.  The one I would like to single out today is &#8220;Code Coverage&#8221;.  That is defined as the percentage of a given source code base that has been executed.  For example, if I have a source code base with 100,000 lines of source code in it and 95,000 of them are verified (by a tool) to have been called, then we have 95% code coverage.  If you can&#8217;t wait and want to know right this second, in this post I will be using <a href="http://www.nunit.org">NUnit</a> for unit testing, <a href="http://www.ncover.com">NCover</a> for code coverage, and <a href="http://www.hudson-ci.org">Hudson</a> for continuous integration.  If you want to learn more about those technologies, I highly recommend <a href="http://www.DimeCasts.Net">DimeCasts.Net</a>, Rob Connery&#8217;s <a href="http://tekpub.com/">TekPub</a>, and <a href="http://channel9.msdn.com/">Channel 9</a>.</p>
<p>Now, even the best developers in the world miss things.  We write a few unit tests, or better yet we&#8217;re doing test-driven development (TDD), and we&#8217;re writing our test first.  We feel good about what we&#8217;re doing and we feel confident our code is being sufficiently test.  That is, of course, until we run a code coverage tool through our source code&#8217;s proverbial hair.</p>
<p>Let&#8217;s talk about &#8220;doing things right&#8221; for a second before we dive into testing and code coverage.  Organization of a software project is vitally important and is best to setup the right way the first time instead of having to go back and try to fix it later.  For a while, I&#8217;ve been laying out (roughly) our Visual Studio solutions in this fashion:<br />
<img src="http://www.wilbloodworth.com/wp-content/uploads/2011/02/SolutionLayout.jpg" alt="Solution Layout" /><br />
&#8220;So what!?&#8221; you might be saying.  I hear ya but stay with me as I&#8217;ll get to why I even bring this up.  If you use this, or a similar, layout, no matter what size project you&#8217;re working on, it will almost always have the same organizational flow.  The real reason I bring this up is because this kind of organization lends itself to a little thing called &#8220;loose coupling&#8221;.  Loose coupling is where the components (or anything for that matter) are physically decoupled.  In this context, it means that we have several (or many) different class libraries (DLLs) that contain code specific to a given development context.  What this means in lay terms is that your TCP communications code is in a separate DLL than your logging code&#8230; i.e. they are physically &#8220;decoupled&#8221;.</p>
<p>Again with the &#8220;so what!?&#8221;.  Well, there is an important distinction when it comes to &#8220;visibility&#8221; and when a source code base lives in many different assemblies/modules/DLLs/et cetera.  What this means is that, assuming you&#8217;re a &#8220;good&#8221; programmer and you&#8217;re using private and protected accessibility modifiers instead of blindly marking everything as public, then those private and protected methods and data members are not (normally) visible outside of the assembly within which they reside.  Since we&#8217;ve chosen the (good) path of loose coupling, and we want to have the highest percentage of code coverage as possible, then we are going to have to test (using unit tests) as many of the source code branches/paths as possible.</p>
<p>Last week, I had a developer tell me, &#8220;I put all my tests in the same assembly as the code it&#8217;s testing, that way I can use the &#8216;internal&#8217; access modifier and test everything from there.&#8221;  As my friend and muse <a href="http://improvingenterprises.com/about/team/leadership/jef-newsom/bio/">Jef Newsom</a> would say, &#8220;Well, that&#8217;s one way to do it.&#8221;  Of course, the rest of us who are tact-challenged would just say you&#8217;re an idiot and we&#8217;d really like to slap you for saying something ridiculous like that.  Let&#8217;s just leave it at &#8220;that&#8217;s a horrible idea and just don&#8217;t do it that way&#8221; so we can continue.</p>
<p>Now that we&#8217;ve got tests in a completely different assembly than the source code those tests are testing, how do we ensure we hit every single code path?  That&#8217;s tough if we&#8217;re doing interface-based programming and we&#8217;re attempting to test solely through an interface.  However, with some &#8220;cool kid&#8221; testing extension methods, we can very easily hit our mark.</p>
<p><a href="http://www.wilbloodworth.com/wp-content/uploads/2011/02/BetterTesting.zip">Before we continue, grab ALL the source code and code coverage files we&#8217;ll be discussing by clicking this line.</a><br />
<strong>NOTE:  </strong><em>This is a Visual Studio 2010 solution and uses C# 4 and thus the .Net framework 4.0.</em></p>
<p>The demo source code is complete and is not some frivolous &#8220;test code&#8221; that is not reusable. The business problem this (demo) code is supposed to solve is to be able to parse a data file with fixed-length records (like old COBOL record) and create domain objects from the data in the file.  The code should keep track of when it runs into &#8220;bad&#8221; data but continue to process the entire data file.</p>
<p>I wrote most of this code using TDD and somewhat decent &#8220;best practices&#8221; all around.  When I fired up NCover to see how much code had actually been tested by my unit tests, I was woefully disappointed to see the following:</p>
<p><img src="http://www.wilbloodworth.com/wp-content/uploads/2011/02/BetterTestingCC1.jpg" alt="Code Coverage 1" /><br />
<a href="http://www.wilbloodworth.com/wp-content/uploads/2011/02/NCover/NCover_Report1/NCover_Report/fullcoveragereport.html">View the first NCover Report HTML by clicking this link</a></p>
<p>What?!  Are you kidding me?  But I tested the entire interface!  Or did I?  Yes, I had been working for 14+ hours at the time so what could I have missed?! <sarcasm>  What I had done was test all the edge cases to ensure I got all those tricky cases&#8230; but I complete forgot to write a test with valid data (doh!).  After I added the normal tests, it improved somewhat to the following:</p>
<p><img src="http://www.wilbloodworth.com/wp-content/uploads/2011/02/BetterTestingCC2.jpg" alt="Code Coverage 2" /><br />
<a href="http://www.wilbloodworth.com/wp-content/uploads/2011/02/NCover/NCover_Report2/NCover_Report/fullcoveragereport.html">View the second NCover Report HTML by clicking this link</a></p>
<p>That is certainly better but I&#8217;m still missing 10.44% of the code branches.  NCover will actually show you exactly what lines of your code are not being called.  Here&#8217;s a view of the NCover report at the source code level (red = not covered, green = covered):<br />
<img src="http://www.wilbloodworth.com/wp-content/uploads/2011/02/BetterTestingCC3.jpg" alt="Code Coverage 3" /></p>
<p>As you can see, some private members&#8217; code paths are not being called.  So, how do we ensure those code paths are called?  We could modify the data file to force those branches to be called.  Or, we could call those methods directly.  &#8220;The hell you say!&#8221;  That other developer we heard from earlier clearly told us it is not possible to call protected and private methods and such&#8230; ah, but he really just wasn&#8217;t thinking deeply enough&#8230; which (FINALLY!) brings us to what I wanted to talk about in the first place&#8230; better testing through some really cool extension methods!</p>
<pre class="brush: csharp">
/* MOST OF THE METHODS LEFT OUT IN AN UNSUCCESSFUL ATTEMPT AT BREVITY FOR THIS BLOG POST */

public static object Call&lt;T&gt;(this T this_, string methodName_, object[] parameters_, Type[] paramTypes_ = null)
{
	const BindingFlags eFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

	MethodInfo methodInfo = GetMethodInfo(this_, methodName_, eFlags, paramTypes_);

	return InvokeMethod(this_, methodInfo, parameters_);
}

private static object InvokeMethod&lt;T&gt;(T this_, MethodInfo methodInfo, object[] parameters_)
{
	// There is currently a &quot;defect&quot; in .NET 4 where a TargetInvocationException is thrown
	// ... when we don&#039;t want it to be throw.  Easiest fix to this problem (for now) is to
	// just catch the exception and rethrow the inner exception which is the exception we
	// are interested in anyway.
	try
	{
		return methodInfo.Invoke(this_, parameters_);
	}
	catch (TargetInvocationException ex)
	{
		throw ex.InnerException;
	}
}

private static MethodInfo GetMethodInfo&lt;T&gt;(T this_, string methodName_, BindingFlags flags_, Type[] paramTypes_ = null)
{
	MethodInfo methodInfo;
	if (paramTypes_ == null)
		methodInfo = this_.GetType().GetMethod(methodName_, flags_);
	else
		methodInfo = this_.GetType().GetMethod(methodName_, flags_, Type.DefaultBinder, CallingConventions.Any, paramTypes_, null);

	if (methodInfo == null)
		throw new MethodNotFoundException(methodName_);

	return methodInfo;
}
</pre>
<p>These methods allow us to call private methods, set private fields, call private static methods, on so on.  Armed with these new tools, we can now knock out those missing tested branches.  Here&#8217;s a sample of how to use these methods:</p>
<pre class="brush: csharp">
[SetUp]
public void SetUp()
{
	_importer = new PersonDataFileImporter();
	_person = new Person();
}

[Test]
public void AddingTheSameIdMoreThanOnce_ExtractIdAddsExceptionToList()
{
	// The ExtractId method needs _currentLine to already be initialized.
	_importer.Set(&quot;_currentLine&quot;, 1);

	var exceptions = _importer.Get(&quot;_exceptions&quot;) as IList&lt;Exception&gt;;
	Assert.IsNotNull(exceptions);
	Assert.AreEqual(0, exceptions.Count);

	// Pass a negative value in for the Id
	_importer.Call(&quot;ExtractId&quot;, new object[] { &quot;1234&quot;, _person });
	Assert.AreEqual(0, exceptions.Count);

	// Now pass the same data to ExtractId again...
	_importer.Call(&quot;ExtractId&quot;, new object[] { &quot;1234&quot;, _person });
	Assert.AreEqual(1, exceptions.Count);
	Assert.IsTrue(exceptions[0].Message.Contains(&quot;already been used&quot;));
}
</pre>
<p>The first thing this test does is set a private data member called _currentLine on the _importer instance to the value of 1.  Then it gets a reference to the private data member called _exceptions on the same _importer instance.  We then make back-to-back calls to the private method called ExtractId with the same Id value of &#8220;1234&#8243;.  This ensures an exception is added because we can&#8217;t two people with the same Id in the same import run.  Nifty huh!</p>
<p>And after creating more tests to fully test all the branches of our code, we can see the final outcome of our code coverage report:<br />
<img src="http://www.wilbloodworth.com/wp-content/uploads/2011/02/BetterTestingCC4.jpg" alt="Code Coverage 4" /><br />
<a href="http://www.wilbloodworth.com/wp-content/uploads/2011/02/NCover/NCover_Report4/NCover_Report/fullcoveragereport.html">View the final NCover Report HTML by clicking this link</a></p>
<p>But wait, why are we only seeing 96.55% branch coverage now?<br />
<img src="http://www.wilbloodworth.com/wp-content/uploads/2011/02/BetterTestingCC5.jpg" alt="Code Coverage 5" /></p>
<p>If you drill down to the offending methods in the NCover report you will see that all of the branches are indeed covered&#8230; so this is a mystery.<br />
<img src="http://www.wilbloodworth.com/wp-content/uploads/2011/02/BetterTestingCC6.jpg" alt="Code Coverage 6" /></p>
<p>Well, I contacted NCover and had a nice long &#8220;Go To Meeting&#8221; conference call with Bryn Brutosky and David Williams (great guys who were extremely helpful and wanted nothing more than to get these problems resolved).  For now, they are looking into it and are going to get back with me soon.  For now, we&#8217;ll just chalk it up and a minor defect that will be fixed soon.  It could be NUnit or .Net 4 that is throwing them off.  It&#8217;s all good though.</p>
<p>There is a TestingBase class in the solution and I&#8217;ll save that and the Hudson discussion for our next blog post as I have drug you through the mud enough for today!<br />
<!-- Begin W3Counter Tracking Code --><br />
<script type="text/javascript" src="http://www.w3counter.com/tracker.js"></script><br />
<script type="text/javascript">
w3counter(31137);
</script><br />
<noscript></p>
<div><a href="http://www.w3counter.com"><img src="http://www.w3counter.com/tracker.php?id=31137" style="border: 0" alt="W3Counter" /></a></div>
<p></noscript><br />
<!-- End W3Counter Tracking Code--></p>
]]></content:encoded>
			<wfw:commentRss>http://wilbloodworth.com/2011/02/03/better-testing-and-code-coverage-with-ncover/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Project Locker &#8211; Free Subversion and Git Repository Hosting</title>
		<link>http://wilbloodworth.com/2011/01/30/project-locker-free-subversion-and-git-repository-hosting/</link>
		<comments>http://wilbloodworth.com/2011/01/30/project-locker-free-subversion-and-git-repository-hosting/#comments</comments>
		<pubDate>Sun, 30 Jan 2011 22:06:26 +0000</pubDate>
		<dc:creator>Wil</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[git]]></category>
		<category><![CDATA[project locker]]></category>
		<category><![CDATA[subversion]]></category>

		<guid isPermaLink="false">http://wilbloodworth.com/blog/?p=311</guid>
		<description><![CDATA[If you&#8217;ve ever accidentally or otherwise lost (possibly a hard drive died) or deleted some of your source code without having a backup, you know that feeling of utter stupidity which can make you physically ill. Not that I have ever had that feeling but if I did, I would be so compelled to find [...]]]></description>
			<content:encoded><![CDATA[<table>
<tbody>
<tr>
<td><a href="http://www.projectlocker.com/"><img class="alignleft size-full wp-image-313" title="ProjectLocker" src="http://wilbloodworth.com/wp-content/uploads/ProjectLocker.jpg" alt="" width="774" height="131" /></a></td>
</tr>
<tr>
<td>If you&#8217;ve ever accidentally or otherwise lost (possibly a hard drive died) or deleted some of your source code without having a backup, you know that feeling of utter stupidity which can make you physically ill.  Not that I have ever had that feeling but if I did, I would be so compelled to find a way to prevent it in the future.</p>
<p>We all &#8220;half ass it&#8221; when we are working on pet projects of our own.  You know you do it!  You cut corners, write code you know you shouldn&#8217;t write just to &#8220;test something out&#8221;.  No worries.  I&#8217;m not saying you&#8217;re a bad person.  I&#8217;ve done it and I still do it at times.  However, the older and (hopefully) wiser I get, the more I come to find value and comfort in doing it right the first time instead of having to &#8220;fix it later&#8221;.</p>
<p>Subversion and Git (currently) are two of the major &#8220;revision control systems&#8221; in use by software developers.  This is not about which is better as that is (usually) a very subjective dialog.  This is more about how to get your precious source code to a safe place so you can rest soundly.</p>
<p>Project Locker (http://www.projectlocker.com/) is a great place to start (and possibly stay).  They offer hosting for both Subversion and Git and you can use either one you choose on a project by project basis.  And if you&#8217;re really into being one of the geeky cool kids, they also offer continuous integration, defect tracking, team collaboration, and document management.  For FREE, you can get an account with three users, 500MB of space, and three projects.  Not bad for free huh!</p>
<p>I&#8217;ve been using them for a few years and have absolutely nothing but great things to say about them.  Check them out.  You won&#8217;t regret it.</td>
</tr>
</tbody>
</table>
<p><!-- Begin W3Counter Tracking Code --><br />
<script src="http://www.w3counter.com/tracker.js" type="text/javascript"></script><br />
 <script type="text/javascript">// <![CDATA[
w3counter(31137);
// ]]&gt;</script><br />
<noscript></p>
<div><a href="http://www.w3counter.com"><img src="http://www.w3counter.com/tracker.php?id=31137" style="border: 0" alt="W3Counter" /></a></div>
<p></noscript><br />
<!-- End W3Counter Tracking Code--></p>
]]></content:encoded>
			<wfw:commentRss>http://wilbloodworth.com/2011/01/30/project-locker-free-subversion-and-git-repository-hosting/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Served from: wilbloodworth.com @ 2012-02-22 12:33:43 -->
