<?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>Bugfree.dk - Ronnie Holm&#039;s blog &#187; Quality</title>
	<atom:link href="http://www.bugfree.dk/blog/tag/quality/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.bugfree.dk/blog</link>
	<description>Not anti-anything, just pro-quality</description>
	<lastBuildDate>Mon, 28 Nov 2011 07:32:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Why not to comment code</title>
		<link>http://www.bugfree.dk/blog/2009/08/15/why-not-to-comment-code/</link>
		<comments>http://www.bugfree.dk/blog/2009/08/15/why-not-to-comment-code/#comments</comments>
		<pubDate>Sat, 15 Aug 2009 19:55:24 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Quality]]></category>
		<category><![CDATA[Refactoring]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/?p=535</guid>
		<description><![CDATA[Update, Aug 18, 2009: I&#8217;m amazed at how much attention this post has received. More than 200 comments on Reddit. I was just listening to the Why comments are evil episode of Deep Fried Bytes. The views put forward by the guest, Corey Haines, deeply resonate with me because I believe they&#8217;re what every developer [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Update, Aug 18, 2009</strong>: I&#8217;m amazed at how much <a href="http://www.reddit.com/r/programming/comments/9b4ct/why_not_to_comment_code">attention</a> this post has received. More than 200 comments on Reddit.
</p>
<p>I was just listening to the <a href="http://deepfriedbytes.com/podcast/episode-35-why-comments-are-evil-and-pair-programming-with-corey-haines">Why comments are evil</a> episode of <a href="http://deepfriedbytes.com">Deep Fried Bytes</a>. The views put forward by the guest, <a href="http://www.coreyhaines.com/">Corey Haines</a>, deeply resonate with me because I believe they&#8217;re what every developer should strive for. I&#8217;m not advocating that code should be entirely free of comments, but rather that most comments do more harm than good.
</p>
<p>Below I&#8217;ve listed the main points of view.
</p>
<ul>
<li>It&#8217;s important to differentiate between code comments and API documentation. For API documentation, don&#8217;t auto-generate. Especially don&#8217;t go with tools like <a href="http://submain.com/products/ghostdoc.aspx">GhostDoc</a>. Take the time to document properly. Otherwise, you&#8217;re more likely to confuse the developer trying to make sense of your code.
</li>
<li>Stop focusing on having the computer understand you and start focusing on the person that comes after you, e.g., while there&#8217;s some overhead to method calls, unless the profiler tells you otherwise, don&#8217;t hesitate to break down a method into as many smaller methods as it takes to make it more approachable.
</li>
<li>Every time you&#8217;re tempted to comment, take the time to think if you can make the code tell its own story, e.g., instead of some branching condition, extract the condition into a method to emphasize the story of why over how.
</li>
<li>Developers comment to explain a confusing part of their code rather than take the time to <a href="http://en.wikipedia.org/wiki/Refactoring">refactor</a> it by extracting a method or naming a variable properly. Inevitably the code gets modified and the comment rots.
</li>
<li>Parts of a method may be complicated so a comment is added. Saying part of a method is complicated is in itself a sign that it&#8217;s doing too much.
</li>
<li>The prevailing culture among developers is to focus on what it takes to get code working. It&#8217;s a battle of short-term vs. long-term maintainability and short-term almost always comes out as the winner. Writing code, ask yourself if you&#8217;re able to immediately understand the code a month from now.
</li>
</ul>
<p>The opinions put forward in the episode aren&#8217;t new. Still, I find them well worth iterating because as developers we tend to not pay enough attention to them. We tend to focus too little on good <a href="http://manifesto.softwarecraftsmanship.org/">software craftsmanship</a>.  </p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2009%2F08%2F15%2Fwhy-not-to-comment-code%2F&amp;title=Why%20not%20to%20comment%20code" id="wpa2a_2"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2009/08/15/why-not-to-comment-code/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Basic logging guidelines</title>
		<link>http://www.bugfree.dk/blog/2009/07/22/basic-logging-guidelines/</link>
		<comments>http://www.bugfree.dk/blog/2009/07/22/basic-logging-guidelines/#comments</comments>
		<pubDate>Wed, 22 Jul 2009 11:28:22 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Logging]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Quality]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/?p=188</guid>
		<description><![CDATA[Next to unit testing I believe in logging to improve the quality of an application. Instrumenting code with logging (or tracing for that matter) should be an integral part of writing production code. Yet, I&#8217;ve often found it not to be the case or that what got logged only made sense to the developer who [...]]]></description>
			<content:encoded><![CDATA[<p>Next to <a href="http://www.bugfree.dk/blog/2009/06/19/basic-unit-testing-guidelines/">unit testing</a> I believe in logging to improve the quality of an application. Instrumenting code with <a href="http://en.wikipedia.org/wiki/Data_logging">logging</a> (or <a href="http://en.wikipedia.org/wiki/Tracing_(software)">tracing</a> for that matter) should be an integral part of writing production code. Yet, I&#8217;ve often found it not to be the case or that what got logged only made sense to the developer who wrote the entry.
</p>
<p>Not logging implies that debugging the application outside the development environment is largely based on guesswork. That’s interesting given that most applications spend the majority of their life running outside the development environment.
</p>
<h4>Life in the sandbox<br />
</h4>
<p>I suspect the absence or low quality of log statements can be, at least partially, explained by developers not finding them useful during development. The debugger available there is generally inferior to the print-lining approach of logging. That said, I&#8217;d argue that many developers don&#8217;t concern themselves enough with how their code behaves in a production environment. Rather than investing a small amount of time in adding log statements up-front, their focus is solely on satisfying functional customer requirements.
</p>
<p>A related case could be made for exception handling. For instance, rather than asserting the validity of an argument up-front and throwing an appropriate exception, the code may later fail with a NullReferenceException. Not throwing the exception up-front, close to where the actual error occurred, one will have a hard time tracking down the issue. Especially since a stack trace with symbols and line numbers is rarely available in a production environment.
</p>
<p>For someone having to resolve the issue, almost any clue as to the cause would be most welcomed. Without a clue that someone would walk around in the dark in the hope of stumbling into a solution.</p>
<h4>End users aren&#8217;t the only users<br />
</h4>
<p>As software developers we have to acknowledge that end users aren&#8217;t the only users of our software. System administrators, developers, and the like should also be factored in during development. Especially since the cost of instrumenting code at key places, early on, doesn&#8217;t add significantly to the overall development cost. Focusing on what can go wrong and communicating it well saves time, money, and frustration down the line. And as a bonus you might create better self-documenting code.
</p>
<p>That said it&#8217;s important to strike a balance between logging too little and too much information. A log should be detailed enough to reveal patterns of use. Ideally, the log should read like a story with short sentences detailing what&#8217;s about to happen, what did or didn&#8217;t happen, and possibly why.
</p>
<p>I&#8217;m not suggesting that we turn logging into a runtime version of <a href="http://en.wikipedia.org/wiki/Literate_programming">literate programming</a>. But simply that sufficient contextual information be provided, i.e., instead of logging &#8220;URL = &#8216;bugfree.dk&#8217;&#8221;, consider the more elaborate &#8220;Retrieving URL for indexing: &#8216;http://bugfree.dk&#8217;&#8221;.
</p>
<h4>Keep your statements clean<br />
</h4>
<p>On the other hand, log statements shouldn&#8217;t be immune to the <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY principle</a>. So make sure to have the logging framework automatically capture common bits of contextual information, such as the date and time of the entry and the class and method within which the log statement originated. On a similar note, don&#8217;t explicitly log when a method is entered or existed. Instead, treat such a case as a cross-cutting concern and take an <a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming">Aspect Oriented</a> approach to logging it.
</p>
<p>Lastly, not every method requires (extensive) logging. Figuring out when and what to log is key. Debugging the application, fixing bugs, and experience should provide guidance into what&#8217;s useful to log.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2009%2F07%2F22%2Fbasic-logging-guidelines%2F&amp;title=Basic%20logging%20guidelines" id="wpa2a_4"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2009/07/22/basic-logging-guidelines/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Basic unit testing guidelines</title>
		<link>http://www.bugfree.dk/blog/2009/06/19/basic-unit-testing-guidelines/</link>
		<comments>http://www.bugfree.dk/blog/2009/06/19/basic-unit-testing-guidelines/#comments</comments>
		<pubDate>Fri, 19 Jun 2009 21:02:39 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Mocking]]></category>
		<category><![CDATA[Presentation]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Quality]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/?p=111</guid>
		<description><![CDATA[Update, Nov 25, 2010: Rather than mimicking the directory structure of the assembly under test in a separate test assembly, I’m now more inclined to keep code under test and test code in the same assembly. Update, Aug 5, 2009: This post grew out of a couple of presentations that I did on the subject [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Update, Nov 25, 2010:</strong> Rather than mimicking the directory structure of the assembly under test in a separate test assembly, I’m now more inclined to <a href="http://weblogs.asp.net/bsimser/archive/2008/04/09/unit-test-projects-or-not.aspx">keep code under test and test code in the same assembly</a>. </p>
<p><b>Update, Aug 5, 2009</b>: This post grew out of a couple of presentations that I did on the subject back in May and June. Here are my slides from <a href="http://www.bugfree.dk/blog/wp-content/uploads/2009/08/Unit-testing-and-mocking.pdf">The Unit testing and mocking presentation</a>. Among other things, they contain a few C# samples elaborating on some of the points below.</p>
<p>This post is born of the need to formalize a set of guidelines on how to write and organize tests. In the past I couldn’t help feeling that with the lack of guidelines I had to start over explaining my views on every new project. With no guidelines the tests written quickly grew unmaintainable, giving unit testing a bad name.</p>
<h4>Why unit test</h4>
<p>Unit testing done right helps build confidence in the code base and drives forward development. Both in terms of forcing one to reflect on the requirements by authoring tests, but also by providing a foundation for developing more modular and testable code.</p>
<p>Given the <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity">cyclomatic complexity</a> of even simple methods, however, not every path through a method is worth exercising with a test. Instead, focus on writing representative unit tests for good and bad scenarios.</p>
<h4>Unit test != integration test</h4>
<p>For object-oriented code a unit test is one that exercises a class in isolation, without the code under test relying on other classes to carry out its operation. Similarly, a unit test shouldn&#8217;t rely on the presence of a database or a key/value pair in a configuration file for it to run. If it did, it would be an integration test. Not that there&#8217;s anything wrong with integration tests. They just take on more dependencies and hence tend to be more brittle. And so they cause more false positives because some dependent part isn&#8217;t properly configured. The key point, though, is not to confuse unit testing with integration testing.</p>
<p>Typically, an object delegates part of its operation to other objects. Writing modular and testable code therefore involves the application of design patterns, such as <a href="http://www.martinfowler.com/articles/injection.html#SignificantRevisions">Inversion of Control (IoC)</a>. With IoC a test can inject (fake) components into the object under test. The fake components share their interfaces with the real ones, but the test controls how they interact with the object under test and hence how the object under test behaves.</p>
<h4>Keep up quality</h4>
<p>As tests are written it&#8217;s vital for the understandability and maintainability of the test suite to keep them small and focused. As a rule of thumb a test should amount to no more than 10-15 lines of code. Longer tests are indicative of too much functionality being tested at once or that code common to multiple tests should be refactored into helper methods.</p>
<p>In terms of quality, the code comprising the tests should be of production code quality, i.e., the code must be kept clean and refactored as the need arises. Otherwise, tests will start to emit the <a href="http://martinfowler.com/bliki/CodeSmell.html">classic code smells</a>. In the longer run code smells lead to tests that are not maintainable and for the time that went into writing them to be wasted.</p>
<h4>Organizing test code</h4>
<p>Assuming the use of Visual Studio (VS), for each VS project with code that one wants to test, create matching projects that host the various kinds of tests, i.e., for the Acme.Intranet.Search project, create the following test related projects:</p>
<pre>    Acme.Intranet.Search.Common
    Acme.Intranet.Search.UnitTest
    Acme.Intranet.Search.IntegrationTest</pre>
<p>The Acme.Intranet.Common project is optional and may include code that is shared between test projects, such as custom assertions. As for the Acme.Intranet.Search.UnitTest project it should be fairly self-contained. One should be able to move the common assembly, the test assembly, and the business code assembly to another machine and have the tests execute there without further setup. Should a test rely on, say, a data file with test data, then include the file as an embedded resource within the test assembly.</p>
<p>Finally, within each test project, a class should be created for each class under test. In addition, the directory structure should match the namespace structure of the class under test, e.g., suppose the fully qualified name of a class is Acme.Intranet.Search.Business.Crawler, then create the following directory structure within the test assembly:</p>
<pre>    Acme.Intranet.Search.UnitTest
        Acme
            Intranet
                Search
                    Buesiness
                        CrawlerTest.cs</pre>
<p>While it’s important to write tests, it’s even more important to know where to put and find tests for a given functional area.</p>
<h4>Naming tests</h4>
<p>As far as naming and structure goes, a test should look something along these lines:</p>
<pre class="prettyprint lang-cs">    [TestClass]
    public class SomeClassTest {
        [TestMethod]
        public void SomeMethod_should_set_error_message_when_no_                    connection_string_is_configured() {
            // arrange
            // act
            // assert
        }
    }</pre>
<p>The test should generally start with the name of the method or property being tested, followed by the word &quot;should&quot; followed by the successful outcome in a descriptive form. Because names of tests tend to be longer than those of regular methods, underscores are used for ease of readability. In addition, the body of most tests should be composed of three parts: (1) the arrange part that sets up the object under test and possibly injects fake dependencies into it. (2) The act part then exercises the method under test, and finally (3) the assert part that verifies that expected state and/or behavioral changes did indeed take place.</p>
<h4>Gathering metrics</h4>
<p>Whenever a build is kicked of (on a build server) it should exercise all tests. Should a test fail, it should cause the entire build to fail, stressing the importance of keeping tests green at all times. Furthermore, a build report should include basic metrics such as code coverage, number of tests run, time spend running the tests, and so forth.</p>
<p>Keep in mind, though, that a high degree of code coverage isn&#8217;t a goal in itself. Instead, focus on writing solid, focused, and representative tests that eventually drive up code coverage.</p>
<h4>Tooling</h4>
<p>As far as .Net and tooling goes, <a href="http://en.wikipedia.org/wiki/MSTest">MSTest</a> or <a href="http://nunit.org">NUnit</a> should be used in concert with <a href="http://www.bugfree.dk/blog/2009/02/11/an-example-of-unit-testing-using-typemock">TypeMock</a> or <a href="http://ayende.com/projects/rhino-mocks.aspx">Rhino Mocks</a>. The use of TypeMock may be preferred over Rhino Mocks because of its unique approach to mocking. TypeMock doesn&#8217;t create fake objects by emitting MSIL and dynamically loading a runtime-generated assembly into the test runner. Instead, TypeMock hooks into the CLR APIs and intercepts calls as the unit test executes. From a coding point of view the TypeMock approach may not change much, but from a functionality point of view it enables the testing of legacy code or new code not written with IoC in mind.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2009%2F06%2F19%2Fbasic-unit-testing-guidelines%2F&amp;title=Basic%20unit%20testing%20guidelines" id="wpa2a_6"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2009/06/19/basic-unit-testing-guidelines/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>An example of unit testing using TypeMock</title>
		<link>http://www.bugfree.dk/blog/2009/02/11/an-example-of-unit-testing-using-typemock/</link>
		<comments>http://www.bugfree.dk/blog/2009/02/11/an-example-of-unit-testing-using-typemock/#comments</comments>
		<pubDate>Wed, 11 Feb 2009 04:00:07 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[Mocking]]></category>
		<category><![CDATA[Quality]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/2009/02/11/an-example-of-unit-testing-using-typemock/</guid>
		<description><![CDATA[This post details my first use of TypeMock, a commercial mocking framework, for testing a web part that displays a dropdown bound to a LINQ query. Based on the item selected, the web part then displays a result bound to another LINQ query. For the purpose of becoming familiar with TypeMock, though, the focus of [...]]]></description>
			<content:encoded><![CDATA[<p>This post details my first use of <a href="http://www.typemock.com">TypeMock</a>, a commercial mocking framework, for testing a web part that displays a dropdown bound to a LINQ query. Based on the item selected, the web part then displays a result bound to another LINQ query. For the purpose of becoming familiar with TypeMock, though, the focus of this post is on testing the code that initializes the LINQ data context. It does so by reading a connection string from a configuration file and passing it to the data context.
</p>
<p>In order to test code whose branching behavior depends on a value read from a configuration file, the test should provide various inputs and assert that the code under test acts accordingly. In addition, the test should run in milliseconds to encourage frequent runs and it should be self-contained, meaning no setup should be required before running the test. These requirements are best met with the web part running in a controlled environment. Yet, as far as the code under test goes, it should behave as if part of an Asp.Net page.
</p>
<p>For the sake of brevity, here&#8217;s my web part with the code to initialize the data context:</p>
<pre class="prettyprint lang-cs">
    public class MyWebPart : WebPart {
        MyDataContext _db;    /* LINQ database context */
        string _error;        /* Early stage error message */    	

        public MyWebPart() {
            Initialize();
        }

        private void Initialize() {
            string c = GetMyConnectionString();
            if (c == null)
                 _error = "Unable to do something";
            else
                _db = new MyDataContext(c);
        }

        private string GetMyConnectionString() {
            System.Configuration.ConnectionStringSettings c =
                System.Configuration.ConfigurationManager.
                    ConnectionStrings["MyConnection"];
            return c == null ? null : c.ConnectionString;
        }

        protected override void Render(HtmlTextWriter w) {
            // display error message if set
        }
    }
</pre>
<p>Notice how the constructor calls out to an Initialize method. Otherwise code within the constructor would fire before I&#8217;d have a chance to setup a controlled environment around the web part and I wouldn&#8217;t be able to test it. Turning the attention to Initialize itself, it’s made up of only a simple if statement. The idea is that if I can&#8217;t mock something as simple as reading a value from a configuration file, most likely I can&#8217;t mock something more involved either. On the other hand, for a developer already familiar with TypeMock and test first development, the code above may be born of the need to satisfy a failing test.
</p>
<p>I want to test Initialize by controlling how GetMyConnectionString gets to return the connection string. While running in an Asp.Net context, GetMyConnectionString would attempt to read the string from web.config. Within my controlled environment, however, I want to inject into the web part an alternate implementation that returns a value of my choosing. That way I can control the path through Initialize and inspecting the state of the  _error or _db fields, I&#8217;m able to determine if the code behaved as intended.
</p>
<p>Using the method chaining DSL of TypeMock, the test takes on this form (of course, having more tests, I&#8217;d move shared code into helper methods decreasing the test to code ratio):
</p>
<pre class="prettyprint lang-cs">
    [TestClass, ClearMocks]
    public class MyWebPartTest {
        [TestMethod, Isolated, VerifyMocks]
        public void Should_set_error_message_when_no_
                    connection_string_is_configured() {
            // arrange
            MyWebPart fake = Isolate.Fake.Instance&lt;MyWebPart&gt;();
            Isolate.NonPublic.WhenCalled(fake,
                "Initialize").CallOriginal();
            Isolate.NonPublic.WhenCalled(fake,
                "GetMyConnectionString").WillReturn(null);
            PrivateObject handle = new PrivateObject(fake);

            // act
            handle.Invoke("Initialize", null); 

            // assert
            Isolate.Verify.NonPublic.WasCalled(fake,
                "GetMyConnectionString");
            string error = (string)handle.GetField("_error");
            MyDataContext ctx = (MyDataContext)handle.GetField("_db");
            Assert.AreEqual("Unable to do something", error);
            Assert.AreEqual(null, ctx);
        }
    }
</pre>
<p>There&#8217;re three parts to tests using TypeMock: (1) the arrange part sets up expectations of what’s going to happen when a method, a property, or some other part of the code under test is invoked; (2) the act part carries out the actual interaction with the object under test, turning to <a href="http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.privateobject.aspx">PrivateObject</a> to invoke the Initialize method; and finally (3) the assert part verifies that what was supposed to happen did happen. Worth noting is that this test asserts both state and behavior, i.e., as part of executing the code under test, _error or _db should&#8217;ve been set to an appropriate state and GetMyConnectionString should’ve been called once and only once.
</p>
<p>This concludes my example, which I believe illustrates the basics of testing and mocking using MS Test and TypeMock. Comparing and contrasting TypeMock to <a href="http://weblogs.asp.net/rosherove/archive/2007/04/26/choosing-a-mock-object-framework.aspx">other popular mocking frameworks</a>, TypeMock has the distinct feature that it can mock almost anything, with or without using interfaces. <a href="http://www.mockobjects.com/2007/03/stop-designing-for-testability.html">Some</a> argue that not enforcing the use of interfaces is also the disadvantage of TypeMock, because for code to be truly testable, it should be modularized using the <a href="http://en.wikipedia.org/wiki/Inversion_of_control">Inversion of Control principle</a>. However, with legacy code, such as the .Net framework or the SharePoint API, to me TypeMock appears to bridge the two worlds nicely, leaving the developer in charge.</p>
<p>To learn more about the basic concepts of mocking, Inversion of Control, and Dependency Injection (containers), I&#8217;d recommend listening to a couple of <a href="http://altnetpodcast.com">Alt.Net podcasts</a>: <a href="http://altnetpodcast.com/episodes/5-di-and-ioc">Dependency Injection and Inversion of Control</a> and <a href="http://altnetpodcast.com/episodes/6-more-di-and-ioc">More Dependency Injection and Inversion of Control</a>.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2009%2F02%2F11%2Fan-example-of-unit-testing-using-typemock%2F&amp;title=An%20example%20of%20unit%20testing%20using%20TypeMock" id="wpa2a_8"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2009/02/11/an-example-of-unit-testing-using-typemock/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Asp.Net error handling by HttpModule</title>
		<link>http://www.bugfree.dk/blog/2008/08/30/aspnet-error-handling-by-httpmodule/</link>
		<comments>http://www.bugfree.dk/blog/2008/08/30/aspnet-error-handling-by-httpmodule/#comments</comments>
		<pubDate>Sat, 30 Aug 2008 21:58:29 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Quality]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/2008/08/30/aspnet-error-handling-by-httpmodule/</guid>
		<description><![CDATA[Download EmailingExceptionModule-1.0.zip. In any real-world application, unhalted exceptions are an unavoidable fact of life. Such exceptions should occur relatively infrequently, but when they do some kind of supporting infrastructure better be in place to capture the when and why of the exceptions. As a developer, you should have the ability to perform a postmortem analysis [...]]]></description>
			<content:encoded><![CDATA[<p>Download <a href="/software/EmailingExceptionModule-1.0.zip">EmailingExceptionModule-1.0.zip</a>.</p>
<p>In any real-world application, unhalted exceptions are an unavoidable fact of life. Such exceptions should occur relatively infrequently, but when they do some kind of supporting infrastructure better be in place to capture the when and why of the exceptions. As a developer, you should have the ability to perform a postmortem analysis on what went wrong and learn from it. Paramount to such analysis is capturing and logging sufficient information at the point of failure.</p>
<p>What this post covers is the thoughts and development of an Asp.Net HttpModule that captures and emails such unhalted exception information to a designated email address.
</p>
<p>To be clear, the goal of the EmailingExceptionModule isn&#8217;t to prevent unhalted exception from occurring per se. Within code, a developer may not know how to handle an exception, and so the exception should rightfully propagate the call stack. In case no caller steps in and handles the exception, the best choice is most likely to terminate the application. It&#8217;s almost always better to be upfront with the user than conceal the possibly inconsistent state of the application.
</p>
<p>So when does the EmailingExceptionModule come in handy then? One scenario is that of <a href="http://msdn.microsoft.com/en-us/vcsharp/aa336812.aspx">C# unchecked exceptions</a>, where the compiler doesn&#8217;t force the caller to catch all types of exceptions thrown by the callee. Unchecked exceptions may materialize as type cast or null reference exceptions when accessing variables. What unchecked exceptions boil down to is that, given the <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity">cyclomatic complexity</a> of some methods, it&#8217;s impractical to manually work through every conceivable path of execution ahead of time. Another scenario is problems with the runtime environment, such as out of disk space or database server down. Nonetheless, some map of the path to failure is helpful in preventing others going down that same path.</p>
<p><img src="http://www.bugfree.dk/blog/wp-content/uploads/2008/08/emailexceptionmoduleexample.png" /><br />
(Summary part of example email. Click <a href="http://www.bugfree.dk/blog/wp-content/uploads/2008/08/emailexceptionmoduleexample.html" target="_blank">here</a> for complete output.)</p>
<p>With web applications, we can take advantage of the application running in a centralized environment. In the spirit of Microsoft&#8217;s <a href="http://en.wikipedia.org/wiki/Dr._Watson_(debugger)">Doctor Watson</a> technology, we can register our own web application error handler and hook it into the Http request pipeline, and have the application execute our code on unhalted exceptions. In practice, such an error handler is implemented either through the Application_Error method of an application&#8217;s <a href="http://en.wikipedia.org/wiki/Global.asax">Global.asax</a> or by loading an <a href="http://msdn.microsoft.com/en-us/library/bb398986.aspx">HttpModule</a> into the application.
</p>
<p>Hinted by the title, I went for the HttpModule. The reason may best be understood by taking a peak behind the .Net curtains: Global.asax is a filename hardwired into the framework so that whenever an application is first hit, the framework asks HttpApplicationFactory, an internal <a href="http://www.ondotnet.com/pub/a/dotnet/2003/08/11/factorypattern.html">factory</a> class, for an <a href="http://msdn.microsoft.com/en-us/library/system.web.httpapplication.aspx">HttpApplication</a> representing the application (there&#8217;s a unique one for each virtual application). As part of manufacturing the HttpApplication, the factory locates the application&#8217;s Global.asax, compiles it into a dynamically generated DLL, loads the DLL, and reflects over the Global.asax class looking for methods adhering to the convention of modulename_eventname. Methods found, such as Application_Error, are then stored in a list of <a href="http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.aspx">MethodInfo</a>s and passed along to HttpApplication. Then, during HttpApplication initialization, events are bound to the methods within Global.asax.</p>
<p>That&#8217;s how Application_Error of Global.asax gets called even though the method isn&#8217;t overriding a base class implementation as is typical for the <a href="http://en.wikipedia.org/wiki/Template_method_pattern">template pattern</a>. That&#8217;s also why code within global.asax isn&#8217;t binary reusable across applications. An HttpModule, on the other hand, can be loaded into any number of applications.
</p>
<p>In practice, implementing an HttpModule it a matter of creating a class that implements the <a href="http://msdn.microsoft.com/en-us/library/system.web.ihttpmodule.aspx">IHttpModule</a> interface:
</p>
<pre class="prettyprint lang-cs">
   public interface IHttpModule {
      void Init(HttpApplication context);
      void Dispose();
   }
</pre>
<p>The crux of error handling with Asp.Net is the <a href="http://msdn.microsoft.com/en-us/library/system.web.httpapplication.error.aspx">Error</a> event of HttpApplication. The easiest way to hook up the event to a method is within the <a href="http://msdn.microsoft.com/en-us/library/system.web.ihttpmodule.init.aspx">Init</a> method of the class. In addition, we assign the application object to a field so that later we can access the most recently thrown exception through it:</p>
<pre class="prettyprint lang-cs">
   public class EmailingExceptionModule : IHttpModule {
      private HttpApplication _application;

      public void Init(HttpApplication a) {
         _application = a;
         _application.Error += OnUnhaltedException;
      }

      public void Dispose() {}

      private void OnUnhaltedException(object sender, EventArgs e) {
         Exception ex = _application.Server.GetLastError().InnerException;
         // Implementation left out for brevity. Please download source
      }
   }
</pre>
<p>The OnUnhaltedException method is where to add code that collects information about the exception and the environment, and that composes and ships the email. Depending on the environment, you may find the need to include additional information in the email. Given the source code, adding to the email is a matter of adding key/value pairs in the form of labels and values to a dictionary. Each dictionary then gets rendered as a table of the key and value columns.
</p>
<p>To have an Asp.Net application load the EmailingExceptionModule and to configure its email related settings, add the following nodes to the application&#8217;s web.config:
</p>
<pre class="prettyprint lang-xml">
   &lt;configuration&gt;
      &lt;appSettings&gt;
         &lt;add key="EmailingExceptionModule_SenderAddress" value="sender@domain.com"/&gt;
         &lt;add key="EmailingExceptionModule_ReceiverAddress" value="receiver@domain.com"/&gt;
         &lt;add key="EmailingExceptionModule_SmtpServer" value="mail.domain.com"/&gt;
         &lt;add key="EmailingExceptionModule_SubjectPrefix" value="MyApp: "/&gt;
      &lt;/appSettings&gt;
      &lt;system.web&gt;
         &lt;httpModules&gt;
            &lt;add name="EmailingExceptionModule" type="Holm.AspNet.EmailingExceptionModule,
                       EmailingExceptionModule, Version=1.0.0.0, Culture=neutral,
                       PublicKeyToken=13806f613f05e959"/&gt;
         &lt;/httpModules&gt;
      &lt;/system.web&gt;
   &lt;/configuration&gt;
</pre>
<p>So what&#8217;s the user experience of unhalted exceptions? Outside the confines of the EmailingExceptionModule, there&#8217;s no indication that the application took note of what happened. Depending on the user&#8217;s profile, it might be helpful to prompt for additional information at the crash point. Or perhaps turn to the <a href="http://blogs.msdn.com/angus_logan/archive/2007/11/07/announcment-windows-live-messenger-im-control-presence-api-conversations-from-web-to-client-querying-presence.aspx">Windows Live Messenger IM Control &amp; Presence API</a> and have the user engage in an MSN conversation with a developer.
</p>
<p>What&#8217;s the advantage of emailing developers unhalted exceptions over storing the information in the file system or a database? I believe in keeping things simple and practical, and handing off information to the file system or a database isn&#8217;t. Most likely the information will end up gathering virtual dust on some server. The email approach, on the other hand, is a proactive, visible, and efficient means to the end of rapidly course-correcting for wrong assumptions.</p>
<p><b>Update, Sep 15</b>: While you <a href="http://www.elumenotion.com/Blog/Lists/Posts/Post.aspx?ID=23">don&#8217;t need a PDB file to debug code</a> through Visual Studio (that&#8217;s what &lt;compilation debug=&#8221;true&#8221;&gt; in web.config is for), the PDB file is required for the <a href="http://timstall.dotnetdevelopersjournal.com/deploying_pdbs_to_get_the_exact_line_number_of_an_exception.htm">stack trace to contain line numbers</a>. Since the PDB file typically has to reside next to the corresponding DLL for the .Net runtime to pick it up, the PDB file may need to be deployed to the GAC along with the DLL. Refer to the first three paragraphs of the &#8220;Debugging assemblies that live in the GAC&#8221; section of <a href="http://blogs.msdn.com/markarend/archive/2008/09/09/debugging-web-parts-and-other-sharepoint-custom-code.aspx">this</a> post for how to GAC deploy PDB files.
<p>For a centrally deployed Asp.Net application, it may be acceptable to ship and deploy the PDB file with the application. Keep in mind, though, that because the PDB file is a mapping of locations in the IL to the source file, having access to the PDB file makes it easier for someone to reverse engineer the code. It&#8217;s also possible to <a href="http://timstall.dotnetdevelopersjournal.com/getting_file_and_line_numbers_without_deploying_the_pdb_file.htm">get at line numbers without the PDB file</a> being deployed, but the approach is somewhat involved. Based on the mapping nature of the PDB file, the idea is to write out IL offsets as part of the exception and to post-process the offsets using a PDB file at a separate location.</p>
<p>Yet another alternative to shipping the PDB file is to setup a symbol server. With <a href="http://blogs.msdn.com/rmbyers/archive/2007/06/21/customizing-pdb-lookup-for-source-information-in-stacktrace.aspx">this</a> nifty piece of code, the <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx">StackTrace</a> class loads the PDB file of the symbol server, adding line numbers to the stack trace.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2008%2F08%2F30%2Faspnet-error-handling-by-httpmodule%2F&amp;title=Asp.Net%20error%20handling%20by%20HttpModule" id="wpa2a_10"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2008/08/30/aspnet-error-handling-by-httpmodule/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

