<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/atom10full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" gd:etag="W/&quot;CEABQ3Y5cCp7ImA9WhdUFUg.&quot;"><id>tag:blogger.com,1999:blog-2788569112547349568</id><updated>2011-10-02T11:52:32.828+01:00</updated><category term="ruby" /><category term="acceptance testing" /><category term="Coding Style" /><category term="mocks" /><category term="Lean" /><category term="Waste" /><category term="reflection" /><category term="Architecture" /><category term="Campfire" /><category term="dtd" /><category term="Leaky Abstractions" /><category term="Build and Deployment" /><category term="github" /><category term="SQLite" /><category term="Gotchas" /><category term="Security" /><category term="ASPX" /><category term="ASP.NET MVC" /><category term="ASP.NET" /><category term="Web" /><category term="WebDriver" /><category term="HTTP" /><category term="Quality" /><category term="XmlSerializer" /><category term="Languages" /><category term="git" /><category term="QCon" /><category term="windows" /><category term="dotnet" /><category term="nullable types" /><category term="xml" /><category term="LINQ" /><category term="Continuous Integration" /><category term="REST" /><category term="NSynthesis" /><category term="Castle.ActiveRecord" /><category term="Code Quality" /><category term="Lessons Learned" /><category term="Refactoring" /><category term="C#" /><category term="Conferences" /><category term="iTunes" /><category term="Functional Programming" /><category term="generics" /><category term="NHibernate" /><category term="Collaboration" /><category term="version control" /><category term="testing" /><category term="Object Oriented Programming" /><category term="mercurial" /><category term="HTML encoding" /><title>Alex Scordellis</title><subtitle type="html" /><link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://alexscordellis.blogspot.com/feeds/posts/default" /><link rel="alternate" type="text/html" href="http://alexscordellis.blogspot.com/" /><author><name>Alex Scordellis</name><uri>http://www.blogger.com/profile/04874376446759200232</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://3.bp.blogspot.com/_xSv6Z4_T9iE/TDyeFksaK2I/AAAAAAAAAJg/AjTKq_entbo/S220/P1030192_2_export.jpg" /></author><generator version="7.00" uri="http://www.blogger.com">Blogger</generator><openSearch:totalResults>21</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/atom+xml" href="http://feeds.feedburner.com/alexscordellis" /><feedburner:info uri="alexscordellis" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><entry gd:etag="W/&quot;A0IFSXkyeCp7ImA9Wx5bGEs.&quot;"><id>tag:blogger.com,1999:blog-2788569112547349568.post-841407435584543814</id><published>2010-11-04T11:18:00.001Z</published><updated>2010-11-04T11:18:38.790Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-11-04T11:18:38.790Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Web" /><category scheme="http://www.blogger.com/atom/ns#" term="HTTP" /><category scheme="http://www.blogger.com/atom/ns#" term="REST" /><category scheme="http://www.blogger.com/atom/ns#" term="Architecture" /><title>RESTful architecture: what should we PUT?</title><content type="html">&lt;p&gt;I've recently been reading &lt;a href="http://restinpractice.com/"&gt;REST In Practice&lt;/a&gt;, by &lt;a href="http://twitter.com/iansrobinson"&gt;Ian Robinson&lt;/a&gt;, &lt;a href="http://twitter.com/jimwebber"&gt;Jim Webber&lt;/a&gt; and &lt;a href="http://twitter.com/savasp"&gt;Savas Parastatidis&lt;/a&gt;. I had some knowledge of the hypermedia-driven architectural style, but this book has really helped me clarify my understanding of both the how and why. It's also convinced me that I should definitely consider Atom for event-based integration requirements.&lt;/p&gt;  &lt;p&gt;There was one concept I found puzzling. In Chapter 5 (the callout box on page 114, if you have the book), the authors recommend using POST to update the state of a resource. This is driven by a choice of interpretation of the semantics of PUT. According to the &lt;a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html"&gt;HTTP spec&lt;/a&gt;:&lt;/p&gt;  &lt;blockquote&gt;If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server.&lt;/blockquote&gt;  &lt;p&gt;In the book, the authors interpret this to mean that the body enclosed with the PUT request should contain the same elements as the representation served by GET requests at the same URI. Since we are using the &lt;a href="http://en.wikipedia.org/wiki/HATEOAS"&gt;HATEOAS&lt;/a&gt; style, representations include links and other hypermedia controls. The implication is therefore that clients should PUT representations containing both business data (for example the new contents of the coffee order) and hypermedia controls (the available next steps in the workflow). To quote the book:&lt;/p&gt;  &lt;blockquote&gt;this obliges a client to PUT all the resource state, including any links, as part of the representation it sends&lt;/blockquote&gt;  &lt;p&gt;The problem here is that the client has no business determining what workflow steps are available. It's the server's job to understand what steps are available given the current resource state, and advertise those to clients using hypermedia controls. Therefore, we don't want the client to send the complete representation including both data and hypermedia controls.&lt;/p&gt;  &lt;p&gt;I see four potential resolutions to this conflict:&lt;/p&gt; &lt;dl&gt;&lt;dt&gt;&lt;strong&gt;Use PATCH&lt;/strong&gt;&lt;/dt&gt;&lt;dd&gt;The PATCH HTTP verb is designed to explicitly support partial updates to a resource. However it's not widely supported. It also feels semantically wrong to me. From the client's point of view, the business data comprising an order (how many lattes?) is the whole resource. The client doesn't see this as a PATCH, but as a replacement, i.e. a PUT. PATCH might make sense to express concepts like &amp;quot;use skimmed milk in the latte, instead of the full fat I originally ordered&amp;quot;.&lt;/dd&gt;&lt;dt&gt;&lt;strong&gt;Use POST&lt;/strong&gt;&lt;/dt&gt;&lt;dd&gt;This is the approach suggested in the book. For me, it has similar drawbacks to PATCH. POST implies appending to a resource. POSTing one cappuccino to a coffee order resource feels like it should add one cappuccino, not replace the existing set of ordered coffees with one cappuccino.&lt;/dd&gt;&lt;dt&gt;&lt;strong&gt;Use PUT, including hypermedia&lt;/strong&gt;&lt;/dt&gt;&lt;dd&gt;To follow the strict interpretation that PUT should include entire representations, the client sends both the entire new coffee order and whatever hypermedia controls the service last sent it. The service then ignores these controls, since it's the service's job to determine what they should be, and on future GETs the service sends whatever controls it deems appropriate at that time. This feels nasty; we are sending unnecessary data just to satisfy some architectural OCD (hat tip to &lt;a href="http://twitter.com/serialseb/status/29652289552"&gt;Seb Lambla&lt;/a&gt; for that phrase!).&lt;/dd&gt;&lt;dt&gt;&lt;strong&gt;Use PUT, don't include hypermedia&lt;/strong&gt;&lt;/dt&gt;&lt;dd&gt;The client sends a complete representation of the new order, but no links. To me, this feels conceptually right. The client fulfils the expectations of PUT by sending a complete representation of the parts of the data for which it is responsible, but does not pretend to be responsible for determining what hypermedia controls are available.&lt;/dd&gt;&lt;/dl&gt;  &lt;p&gt;I explored some of these thoughts through a twitter conversation with &lt;a href="http://twitter.com/serialseb"&gt;@serialseb&lt;/a&gt;, &lt;a href="http://twitter.com/iansrobinson"&gt;@iansrobinson&lt;/a&gt; and &lt;a href="http://twitter.com/jimwebber"&gt;@jimwebber&lt;/a&gt;. Being able to explore these thoughts in conversation with some of the experts is incredibly rewarding, compared to sitting alone pondering, so thanks to those guys for their contributions. Ultimately we came up with a simple rule of thumb, which seemed to attract mutual agreement:&lt;/p&gt;  &lt;blockquote&gt;In response to GET requests, services serve complete representation of the current known state, including business data and available hypermedia controls. Clients PUT complete representations of the parts for which they are responsible. &lt;/blockquote&gt;  &lt;p&gt;HTTP places two significant expectations on PUT requests: idempotency, and the concept that the enclosed entity-body is a complete representation. This rule of thumb satisfies both, while absolving clients of the need to include data over which they have no control or responsibility, provided we accept that GET and PUT representations need not be the same. &lt;/p&gt;  &lt;p&gt;This raises another question. Available hypermedia controls are just one example of representation elements that only the service should be generating. Other examples include service computed values (for example the total cost of a coffee order) and resource state that is owned by the service (for example, whether or not the order has been paid for). We don't want the client updating the total cost, or sending state fields telling the service that the client has paid, when it hasn't. Either of those could be bad for business! Should these data items be included in client PUT requests? My feeling is no. According to the rule of thumb, clients only include the parts for which they are responsible. However I have a feeling that this may be a controversial standpoint. From the &lt;a href="http://twitter.com/#!/jimwebber/statuses/29652788728"&gt;twitter conversation, I learned&lt;/a&gt; that the authors aversion to partial PUT came from none other than &lt;a href="http://www.mnot.net/"&gt;Mark Nottingham&lt;/a&gt;. &lt;/p&gt;  &lt;p&gt;Disclaimer: I hope that I have not misrepresented the viewpoint of the book and its authors. If I have, I apologise and welcome feedback and corrections.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2788569112547349568-841407435584543814?l=alexscordellis.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/alexscordellis/~4/aeBkSHzXsfE" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://alexscordellis.blogspot.com/feeds/841407435584543814/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://alexscordellis.blogspot.com/2010/11/restful-architecture-what-should-we-put.html#comment-form" title="10 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/841407435584543814?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/841407435584543814?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/alexscordellis/~3/aeBkSHzXsfE/restful-architecture-what-should-we-put.html" title="RESTful architecture: what should we PUT?" /><author><name>Alex Scordellis</name><uri>http://www.blogger.com/profile/04874376446759200232</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://3.bp.blogspot.com/_xSv6Z4_T9iE/TDyeFksaK2I/AAAAAAAAAJg/AjTKq_entbo/S220/P1030192_2_export.jpg" /></author><thr:total>10</thr:total><feedburner:origLink>http://alexscordellis.blogspot.com/2010/11/restful-architecture-what-should-we-put.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CEEGRHc6fyp7ImA9WxFWFEw.&quot;"><id>tag:blogger.com,1999:blog-2788569112547349568.post-5455537884430923837</id><published>2010-06-01T18:17:00.001+01:00</published><updated>2010-06-01T18:17:05.917+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-06-01T18:17:05.917+01:00</app:edited><title>Firefox autocomplete plays havoc with hidden input fields</title><content type="html">&lt;p&gt;We recently had a bug in our system which we eventually traced down to some odd Firefox behaviour. We’re using hidden input fields in our HTML to pass various pieces of data from the server to JavaScript code. We found that on some occasions, these hidden input fields would have different values from those sent by the server, even before any JavaScript that could change the values had run.&lt;/p&gt;  &lt;p&gt;We realised that Firefox was using its autocomplete feature to auto-populate the hidden input fields with old values. The problem would only happen when some JavaScript had set the value of the hidden field, then the user pressed F5. The value set by the JavaScript would then reappear after the reload, even though the server sent a different value.&lt;/p&gt;  &lt;p&gt;The solution we found (credit to &lt;a href="http://weblogs.asp.net/jarnold/"&gt;Jim&lt;/a&gt;) is to use the non-standard HTML attribute &lt;code&gt;autocomplete=&amp;quot;off&amp;quot;&lt;/code&gt;. You can also use an invisible span. The following page demonstrates the problem:&lt;/p&gt;  &lt;pre class="html" name="code"&gt;&amp;lt;html&amp;gt;
    &amp;lt;body&amp;gt;
        &amp;lt;input type=&amp;quot;hidden&amp;quot; value=&amp;quot;original&amp;quot; id=&amp;quot;broken&amp;quot;&amp;gt;&amp;lt;/input&amp;gt;
        &amp;lt;input type=&amp;quot;hidden&amp;quot; value=&amp;quot;original&amp;quot; autocomplete=&amp;quot;off&amp;quot; id=&amp;quot;fixed&amp;quot;&amp;gt;&amp;lt;/input&amp;gt;
        &amp;lt;span style=&amp;quot;display: none;&amp;quot; id=&amp;quot;span_not_affected&amp;quot; value=&amp;quot;original&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;
        &amp;lt;script type=&amp;quot;text/javascript&amp;quot; src=&amp;quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js&amp;quot;&amp;gt; &amp;lt;/script&amp;gt;
        &amp;lt;script type=&amp;quot;text/javascript&amp;quot;&amp;gt;
            alert(&amp;quot;input with no autocomplete attribute: &amp;quot; + $(&amp;quot;#broken&amp;quot;).attr(&amp;quot;value&amp;quot;));
            alert(&amp;quot;input with autocomplete attribute: &amp;quot; + $(&amp;quot;#fixed&amp;quot;).attr(&amp;quot;value&amp;quot;));
            alert(&amp;quot;span: &amp;quot; + $(&amp;quot;#span_not_affected&amp;quot;).attr(&amp;quot;value&amp;quot;));
            $(&amp;quot;#broken&amp;quot;).attr(&amp;quot;value&amp;quot;,&amp;quot;changed&amp;quot;);
            $(&amp;quot;#fixed&amp;quot;).attr(&amp;quot;value&amp;quot;,&amp;quot;changed&amp;quot;);
            $(&amp;quot;#span_not_affected&amp;quot;).attr(&amp;quot;value&amp;quot;,&amp;quot;changed&amp;quot;);
        &amp;lt;/script&amp;gt;
    &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;&lt;/pre&gt;

&lt;p&gt;Save this page as an html file and open it in Firefox. You'll get 3 alerts saying 'original', as you might expect. Reload it (F5), however, and the first alert, will say 'changed'. The other two will not be affected. Firefox has remembered the value 'changed' that was set by the JavaScript the first time round and ignored the value in the source HTML.&lt;/p&gt;

&lt;p&gt;I’ve seen this behaviour in Firefox 3.6, but not in any of Chrome, Safari or IE6.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2788569112547349568-5455537884430923837?l=alexscordellis.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/alexscordellis/~4/0l8MpUbUARo" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://alexscordellis.blogspot.com/feeds/5455537884430923837/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://alexscordellis.blogspot.com/2010/06/firefox-autocomplete-plays-havoc-with.html#comment-form" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/5455537884430923837?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/5455537884430923837?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/alexscordellis/~3/0l8MpUbUARo/firefox-autocomplete-plays-havoc-with.html" title="Firefox autocomplete plays havoc with hidden input fields" /><author><name>Alex Scordellis</name><uri>http://www.blogger.com/profile/04874376446759200232</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://3.bp.blogspot.com/_xSv6Z4_T9iE/TDyeFksaK2I/AAAAAAAAAJg/AjTKq_entbo/S220/P1030192_2_export.jpg" /></author><thr:total>1</thr:total><feedburner:origLink>http://alexscordellis.blogspot.com/2010/06/firefox-autocomplete-plays-havoc-with.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CUMERHszeip7ImA9WxBaFEg.&quot;"><id>tag:blogger.com,1999:blog-2788569112547349568.post-2021960582429089485</id><published>2010-03-24T17:56:00.001Z</published><updated>2010-03-24T17:56:45.582Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-03-24T17:56:45.582Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Lean" /><category scheme="http://www.blogger.com/atom/ns#" term="Build and Deployment" /><category scheme="http://www.blogger.com/atom/ns#" term="version control" /><category scheme="http://www.blogger.com/atom/ns#" term="Collaboration" /><category scheme="http://www.blogger.com/atom/ns#" term="Waste" /><category scheme="http://www.blogger.com/atom/ns#" term="Continuous Integration" /><title>So, er, which build label do I deploy this week?</title><content type="html">&lt;h2&gt;The problem&lt;/h2&gt;  &lt;p&gt;A couple of weeks ago our team accidentally deployed the wrong build to our production environment. We deployed that latest green build from &lt;a href="http://confluence.public.thoughtworks.org/display/CCNET/Welcome+to+CruiseControl.NET"&gt;CruiseControl.NET&lt;/a&gt;, rather than the slightly older one that we’d intended. Fortunately, this didn’t matter too much. After all, this build had passed our test suite, so there were no serious bugs.&lt;/p&gt;  &lt;p&gt;We decided to perform some root-cause analysis, using the &lt;a href="http://www.startuplessonslearned.com/2008/11/five-whys.html"&gt;5-Whys technique&lt;/a&gt;, to understand how this had happened. We came up with a few root causes:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;strong&gt;It’s hard to tell what code changes are contained in a given build.&lt;/strong&gt; The only way to do this is to analyse the git commit history, which can be rather tangled. To make this easier, we have now agreed on a convention for git branch naming and merging patterns, based on &lt;a href="http://nvie.com/git-model"&gt;this one&lt;/a&gt; from &lt;a href="https://twitter.com/nvie/"&gt;@nvie&lt;/a&gt;. &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;We were testing stories, not builds.&lt;/strong&gt; This is a natural way to approach a story-driven Agile project, but stories aren’t what gets deployed to production, builds are. Come time to deploy, we’d know that stories #123, #134 and #96 are signed off, but that sign off would be tied to a point in time, not a build number. How do we know what build to deploy for these stories? &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;We didn’t have a way to retrospectively ‘fail’ green cruise builds.&lt;/strong&gt; Just because &lt;a href="http://confluence.public.thoughtworks.org/display/CCNET/Welcome+to+CruiseControl.NET"&gt;CruiseControl.NET&lt;/a&gt; passes a build, it doesn’t mean it’s perfect. When a QA finds a bug during manual or exploratory testing of a story, they fail that story. But we really need to fail that build. We don’t want to deploy this build or any following one until this bug is fixed. &lt;/li&gt; &lt;/ul&gt;  &lt;h2&gt;The solution&lt;/h2&gt;  &lt;p&gt;We came up with a great, low-tech way to solve this problem: coloured stickers!&lt;/p&gt;  &lt;p&gt;&lt;a href="http://lh6.ggpht.com/_xSv6Z4_T9iE/S6pSWQ4ezKI/AAAAAAAAAJY/EjM2nXGQtfw/s1600-h/story-stickers%5B11%5D.jpg" target="_blank"&gt;&lt;img title="in tribute to @markhneedham&amp;#39;s love of foo" style="border-top-width: 0px; display: block; border-left-width: 0px; float: none; border-bottom-width: 0px; margin-left: auto; margin-right: auto; border-right-width: 0px" height="484" src="http://lh3.ggpht.com/_xSv6Z4_T9iE/S6pSWwKlT3I/AAAAAAAAAJc/jsNy1QFanes/story-stickers_thumb%5B9%5D.jpg?imgmax=800" width="644" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;When the developers think that they’ve finished coding a story and that it’s ready for test, they put a white sticker in the bottom left of the story card, and write the build number on. &lt;/li&gt;    &lt;li&gt;If QA pass the story, they stick a green sticker on, with the build number against which they tested written on it. The story is now ready for deployment. &lt;/li&gt;    &lt;li&gt;If they find a problem, they use a red sticker. Again, they write on the sticker the number of the build in which they found the problem. &lt;/li&gt;    &lt;li&gt;When the developer commits their fix to the problem, they use another white sticker labelled with the build number containing the fix. This will be followed by another green or red, and so on. &lt;/li&gt; &lt;/ul&gt;  &lt;h2&gt;&lt;/h2&gt;  &lt;h2&gt;What does this give us?&lt;/h2&gt;  &lt;p&gt;Imagine I want to deploy stories #123, #134 and #96 to production. We know that they’ve all been passed by QA, but we need to answer some more questions.&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;strong&gt;What build contains working versions of all these stories? &lt;/strong&gt;It’s now very easy to answer this: just look at the green stickers on each card. To deploy these stories, we need the latest of the build numbers on the green stickers. &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;Is the build I’m deploying safe to deploy? &lt;/strong&gt;Anything on the wall with a white or red sticker not followed by a green one represents a build containing code that either is known to have a bug or has never been tested. Let’s say we want to deploy build 2503 (it has a green sticker for a story we want to deploy to our users), and the currently deployed build is 2496. If we see a white or red sticker on a story that’s still in test with build 2499 on it, we know that we can’t deploy 2503. The team can now focus on finishing the story that’s carrying the sticker for build 2499, so that we can get these features to our users as quickly as possible. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;What’s great about this is how easy it is to glance at the wall to get the answers to these questions. We don’t have to go digging in our cruise result logs or story tracking tool or the project manager’s spreadsheet.&lt;/p&gt;  &lt;h2&gt;Other benefits&lt;/h2&gt;  &lt;p&gt;Each time a story goes into test and fails, that is waste. In the language of &lt;a href="http://www.poppendieck.com/papers/LeanThinking.pdf"&gt;lean thinking&lt;/a&gt;, we see rework (QA may have to retest areas of functionality after the fix, dev may have to re-code something), transportation (extra handoffs between QA and dev, often delayed if one party is busy working on something else) and waiting (QA and dev waiting for each other to be available for collaboration, dev idling while a story is QAed as they don’t want to pick up a new one and thus have to switch context back to the one in test). We are always looking to minimise waste, so we’d like to reduce the number of trips taken by each story around the dev-QA cycle.&lt;/p&gt;  &lt;p&gt;The number of stickers on each card is an immediate visual indicator of this metric. A quick look at the wall (again, no digging in the story tracking tool!) shows which stories have incurred this type of waste. We might then decide to apply some root-cause analysis and other &lt;a href="http://en.wikipedia.org/wiki/Kaizen"&gt;continuous improvement&lt;/a&gt; activities to those stories, so that we can understand what really caused the waste and prevent it in the future.&lt;/p&gt;  &lt;p&gt;I can’t recall whose idea this was, so credit goes to the whole team. Extra credit to Nick Ashley, who chose the type of stickers to use when I was telling him to use a completely different sort that would have been entirely impractical. &lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2788569112547349568-2021960582429089485?l=alexscordellis.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/alexscordellis/~4/FDXWU7GQmbM" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://alexscordellis.blogspot.com/feeds/2021960582429089485/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://alexscordellis.blogspot.com/2010/03/so-er-which-build-label-do-i-deploy.html#comment-form" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/2021960582429089485?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/2021960582429089485?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/alexscordellis/~3/FDXWU7GQmbM/so-er-which-build-label-do-i-deploy.html" title="So, er, which build label do I deploy this week?" /><author><name>Alex Scordellis</name><uri>http://www.blogger.com/profile/04874376446759200232</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://3.bp.blogspot.com/_xSv6Z4_T9iE/TDyeFksaK2I/AAAAAAAAAJg/AjTKq_entbo/S220/P1030192_2_export.jpg" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh3.ggpht.com/_xSv6Z4_T9iE/S6pSWwKlT3I/AAAAAAAAAJc/jsNy1QFanes/s72-c/story-stickers_thumb%5B9%5D.jpg?imgmax=800" height="72" width="72" /><thr:total>1</thr:total><feedburner:origLink>http://alexscordellis.blogspot.com/2010/03/so-er-which-build-label-do-i-deploy.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DkYEQHg9eCp7ImA9WxBbF0s.&quot;"><id>tag:blogger.com,1999:blog-2788569112547349568.post-8732953981020714036</id><published>2010-03-16T18:28:00.001Z</published><updated>2010-03-16T18:28:21.660Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-03-16T18:28:21.660Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Code Quality" /><category scheme="http://www.blogger.com/atom/ns#" term="Coding Style" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><category scheme="http://www.blogger.com/atom/ns#" term="Quality" /><title>Lambda-passing style for access to resources with lifecycles</title><content type="html">&lt;p&gt;When accessing a resource whose lifecycle must be carefully controlled, such as database or network connections, we would traditionally use a &lt;code&gt;try..finally&lt;/code&gt; or &lt;code&gt;using&lt;/code&gt; block in C#. Something like this:&lt;/p&gt;  &lt;pre class="csharp" name="code"&gt;using(var db = connectionPool.GetConnection())
{
    results = db.ExecuteQuery(query);
}&lt;/pre&gt;

&lt;p&gt;or&lt;/p&gt;

&lt;pre class="csharp" name="code"&gt;DatabaseConnection db = null;
try
{
    db = connectionPool.GetConnection();
    results = db.ExecuteQuery(query);
}
finally
{
    db.Close();
}&lt;/pre&gt;

&lt;p&gt;I'm not really a fan of either of these styles. The &lt;code&gt;try..finally&lt;/code&gt; one is particularly nasty. It would be very easy to forget to call &lt;code&gt;db.Close()&lt;/code&gt;, or to forget to put that call in a &lt;code&gt;finally&lt;/code&gt; block. It’s also unpleasant to have to declare and initialize the &lt;code&gt;db&lt;/code&gt; variable outside the scope of the &lt;code&gt;try&lt;/code&gt; block. Not only is it ugly, but it means that code further down could try to access the database connection once I’ve closed it. &lt;/p&gt;

&lt;p&gt;The &lt;code&gt;using&lt;/code&gt; option isn't quite so bad, but as a client of the connection pool (or whoever is managing my resource), I still have to remember to call &lt;code&gt;Dispose()&lt;/code&gt; or wrap it in a &lt;code&gt;using&lt;/code&gt; block. It also requires that the &lt;code&gt;DatabaseConnection&lt;/code&gt; type expose both the operations (e.g. &lt;code&gt;ExecuteQuery&lt;/code&gt;) and the disposal mechanism, which may more naturally belong on the connection pool.&lt;/p&gt;

&lt;p&gt;I prefer the following style:&lt;/p&gt;

&lt;pre class="csharp" name="code"&gt;var results = connectionPool.WithOpenConnection(c =&amp;gt; c.ExecuteQuery(query));&lt;/pre&gt;

&lt;p&gt;With this style, there's no way we can forget to close the connection. There's also no way that we can access the connection object outside of the intended scope.&lt;/p&gt;

&lt;p&gt;The code inside my connection pool object usually looks like one of the examples above, using &lt;code&gt;using&lt;/code&gt; or &lt;code&gt;try...finally&lt;/code&gt;. I've now managed to confine the use of those unpleasant constructs to just one place in the codebase, rather than repeat them every time I need to use my database.&lt;/p&gt;

&lt;p&gt;Typically, &lt;code&gt;WithOpenConnection&lt;/code&gt; has a generic type parameter to specify the return type. Because C# doesn't allow &lt;code&gt;void&lt;/code&gt; to satisfy a generic type parameter, you typically need to provide two implementations of &lt;code&gt;WithOpenConnection&lt;/code&gt;, one for when your operation has a return value and one when it doesn't. This is the only drawback I can see of this approach.&lt;/p&gt;

&lt;h2&gt;Building Quality In&lt;/h2&gt;

&lt;p&gt;A common theme in lean and agile software delivery is to build quality in. That is, rather than inspect our software for bugs after we’ve written it, we make the software inherently high quality. One way to do this is minimise the opportunity to make a mistake and introduce a bug. If we make it easier to do the right thing, we’re less likely to make a mistake. Sometimes this is referred to as setting ourselves up for success.&lt;/p&gt;

&lt;p&gt;That principle underlies the reasons that I prefer the lambda passing style. It’s impossible to access the database connection and forget to close it, or to access a stale connection, so we should never be able cause a bug that way.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2788569112547349568-8732953981020714036?l=alexscordellis.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/alexscordellis/~4/_jLsLO8IvY0" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://alexscordellis.blogspot.com/feeds/8732953981020714036/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://alexscordellis.blogspot.com/2010/03/lambda-passing-style-for-access-to.html#comment-form" title="3 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/8732953981020714036?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/8732953981020714036?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/alexscordellis/~3/_jLsLO8IvY0/lambda-passing-style-for-access-to.html" title="Lambda-passing style for access to resources with lifecycles" /><author><name>Alex Scordellis</name><uri>http://www.blogger.com/profile/04874376446759200232</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://3.bp.blogspot.com/_xSv6Z4_T9iE/TDyeFksaK2I/AAAAAAAAAJg/AjTKq_entbo/S220/P1030192_2_export.jpg" /></author><thr:total>3</thr:total><feedburner:origLink>http://alexscordellis.blogspot.com/2010/03/lambda-passing-style-for-access-to.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DEYFR3k5eip7ImA9WxBQFUk.&quot;"><id>tag:blogger.com,1999:blog-2788569112547349568.post-4075938595840397507</id><published>2010-01-15T09:01:00.001Z</published><updated>2010-01-15T09:01:56.722Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-01-15T09:01:56.722Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Campfire" /><category scheme="http://www.blogger.com/atom/ns#" term="Collaboration" /><category scheme="http://www.blogger.com/atom/ns#" term="Continuous Integration" /><title>CruiseControl.NET Campfire plugin</title><content type="html">&lt;p&gt;On my current project, we’re using 37Signals’ &lt;a href="http://campfirenow.com/"&gt;Campfire&lt;/a&gt; for team chat and collaboration. We also use &lt;a href="http://ccnet.thoughtworks.com/"&gt;CruiseControl.NET&lt;/a&gt; for &lt;a href="http://martinfowler.com/articles/continuousIntegration.html"&gt;continuous integration&lt;/a&gt;. I thought it would be nice to have CruiseControl.NET automatically post build results into the Campfire chat room, to raise visibility of the build status out of the system tray and into the browser.&lt;/p&gt;  &lt;p&gt;Implementing CruiseControl.NET plugins is quite straightforward, and Campfire has a very simple &lt;a href="http://developer.37signals.com/campfire/"&gt;XML-over-HTTP API&lt;/a&gt; for posting messages into chatrooms. The code for the plugin is &lt;a href="http://github.com/alexscordellis/ccnet.campfire.plugin"&gt;available on my github account&lt;/a&gt;. There are instructions there for using the plugin in your environment.&lt;/p&gt;  &lt;p&gt;For the CruiseControl.NET integration, I found this &lt;a href="http://krisselden.com/2007/01/29/adding-a-custom-cruisecontrolnet-publisher/"&gt;blog post&lt;/a&gt; from Kris Selden very useful. The one thing I wasn’t sure about was how to handle errors. I didn’t want to risk exceptions being thrown from my plugin causing the build to fail. If something’s going to go wrong, I’d rather the plugin failed silently – we’ll quickly notice the lack of messages appearing in Campfire and look into it – so I made sure that I catch all exceptions and use CruiseControl.NET’s &lt;a href="http://logging.apache.org/log4net/index.html"&gt;log4net&lt;/a&gt; facility to write to the server log.&lt;/p&gt;  &lt;p&gt;I did have one problem with the Campfire API. I forgot to set the Content-Type HTTP header. Without this I was getting the HTTP response code 422 Unprocessable Entity, with a message “Body can't be blank”. This confused me for a while as I was definitely sending a well formed XML message with a body element. Setting the Content-Type header to application/xml fixed the problem.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2788569112547349568-4075938595840397507?l=alexscordellis.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/alexscordellis/~4/U6Cz87Vs2lQ" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://alexscordellis.blogspot.com/feeds/4075938595840397507/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://alexscordellis.blogspot.com/2010/01/cruisecontrolnet-campfire-plugin.html#comment-form" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/4075938595840397507?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/4075938595840397507?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/alexscordellis/~3/U6Cz87Vs2lQ/cruisecontrolnet-campfire-plugin.html" title="CruiseControl.NET Campfire plugin" /><author><name>Alex Scordellis</name><uri>http://www.blogger.com/profile/04874376446759200232</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://3.bp.blogspot.com/_xSv6Z4_T9iE/TDyeFksaK2I/AAAAAAAAAJg/AjTKq_entbo/S220/P1030192_2_export.jpg" /></author><thr:total>1</thr:total><feedburner:origLink>http://alexscordellis.blogspot.com/2010/01/cruisecontrolnet-campfire-plugin.html</feedburner:origLink></entry><entry gd:etag="W/&quot;AkUFRHYzeip7ImA9WxNXGUw.&quot;"><id>tag:blogger.com,1999:blog-2788569112547349568.post-3946180739337409282</id><published>2009-10-07T13:17:00.004+01:00</published><updated>2009-10-07T13:23:35.882+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-10-07T13:23:35.882+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Code Quality" /><category scheme="http://www.blogger.com/atom/ns#" term="Refactoring" /><title>Red-Green-Refactor at story level</title><content type="html">A quick thought that came up this morning.

When working on a story, we have two sets of responsibilities:

&lt;ul&gt;
&lt;li&gt;to the acceptance criteria and business value&lt;/li&gt;
&lt;li&gt;to the technical quality of the codebase&lt;/li&gt;
&lt;/ul&gt;

We often forget to attend to the codebase once we've finished attending to the business value. We may end up with an unfinished refactoring. We are often in such a rush to claim the points. It's important that we keep the codebase clean.

Red-Green-Refactor and "&lt;a href="http://c2.com/cgi/wiki?MakeItWorkMakeItRightMakeItFast"&gt;Make it work,  make it right&lt;/a&gt;" apply at the story level as well as the code level. Satisfy the criteria, then make sure you're happy with the code quality.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2788569112547349568-3946180739337409282?l=alexscordellis.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/alexscordellis/~4/HzgmaiBW8ZA" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://alexscordellis.blogspot.com/feeds/3946180739337409282/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://alexscordellis.blogspot.com/2009/10/red-green-refactor-at-story-level.html#comment-form" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/3946180739337409282?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/3946180739337409282?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/alexscordellis/~3/HzgmaiBW8ZA/red-green-refactor-at-story-level.html" title="Red-Green-Refactor at story level" /><author><name>Alex Scordellis</name><uri>http://www.blogger.com/profile/04874376446759200232</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://3.bp.blogspot.com/_xSv6Z4_T9iE/TDyeFksaK2I/AAAAAAAAAJg/AjTKq_entbo/S220/P1030192_2_export.jpg" /></author><thr:total>1</thr:total><feedburner:origLink>http://alexscordellis.blogspot.com/2009/10/red-green-refactor-at-story-level.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CUQMR3c7eip7ImA9WxNREEg.&quot;"><id>tag:blogger.com,1999:blog-2788569112547349568.post-5219885882571494154</id><published>2009-09-04T09:33:00.001+01:00</published><updated>2009-09-04T09:36:26.902+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-09-04T09:36:26.902+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="NHibernate" /><category scheme="http://www.blogger.com/atom/ns#" term="Castle.ActiveRecord" /><title>NHibernate Bidirectional Cascade – when is it appropriate?</title><content type="html">&lt;p&gt;I recently found a situation where I needed to use NHibernate’s cascade facility from both ends of a relationship. Normally, I’d use it only in one direction, but in this scenario the only practical solution was to use it in both directions. I’m unsure whether this is a good thing to do, so in this post I’ll:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;talk about why I normally use it in one direction &lt;/li&gt;    &lt;li&gt;talk about the situation that led to the bidirectional cascade &lt;/li&gt;    &lt;li&gt;ask whether this was the right solution. &lt;/li&gt; &lt;/ul&gt;  &lt;h4&gt;One-directional cascades&lt;/h4&gt;  &lt;p&gt;Normally, the cascade is tied to the concept of ownership in the model. We cascade changes from the parent (e.g. an Order) to its logical children (e.g. OrderLines). This fits in with the &lt;a href="http://en.wikipedia.org/wiki/Domain-driven_design" target="_blank"&gt;Domain-Driven Design&lt;/a&gt; concept of an &lt;a href="http://dddstepbystep.com/wikis/ddd/aggregate-root.aspx" target="_blank"&gt;aggregate root&lt;/a&gt;. If we have the appropriate cascades set up from the aggregate root to the contained entities, then we can follow a simple workflow:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;load up an aggregate root from the repository &lt;/li&gt;    &lt;li&gt;modify, add and remove entities within the aggregate &lt;/li&gt;    &lt;li&gt;let NHibernate automatically persist the changes to the database when the session is flushed &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;This makes for very clean domain layer code which remains persistent ignorant. The domain code that is performing these modifications doesn’t have to explicitly save or delete any of the entities within the aggregate. &lt;/p&gt;  &lt;p&gt;I suppose this model does not say that we can’t have cascade running from children to parents. But I always felt that the natural order of things was to have cascades running in one direction.&lt;/p&gt;  &lt;h4&gt;Why we needed bidirectional cascades&lt;/h4&gt;  &lt;p align="center"&gt;&lt;a href="http://lh3.ggpht.com/_xSv6Z4_T9iE/SqDQ38d79EI/AAAAAAAAAIA/5hjXg-8swOo/s1600-h/transient3.png"&gt;&lt;img title="transient" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="340" alt="transient" src="http://lh4.ggpht.com/_xSv6Z4_T9iE/SqDQ4C4X9vI/AAAAAAAAAIE/uU8VHrDqloY/transient_thumb1.png?imgmax=800" width="644" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;In this scenario, the Customer is an aggregate root containing the ShoppingOrder and OrderLine objects. I’ve set up cascades from the Customer down to the OrderLine class, which allows the following code:&lt;/p&gt;  &lt;pre class="c#" name="code"&gt;using (new SessionScope())
{
    var customer = ActiveRecordMediator&amp;lt;Customer&amp;gt;.FindByPrimaryKey(customerId);
    var shoppingOrder = customer.AddOrder(some, parameters);
    var newOrderLine = shoppingOrder.AddLine(some, parameters);
}&lt;/pre&gt;

&lt;p&gt;which executes SQL like this:&lt;/p&gt;

&lt;pre class="sql" name="code"&gt;SELECT ... FROM Customer WHERE Id = ...
INSERT INTO ShoppingOrder ...
INSERT INTO OrderLine ...&lt;/pre&gt;

&lt;p&gt;Perfect. Note that I’m using &lt;a href="http://www.castleproject.org/activerecord/index.html" target="_blank"&gt;Castle.ActiveRecord&lt;/a&gt; to configure and access NHibernate, with auto-flushing sessions. As far as I know, this scenario would translate directly to an equivalent plain NHibernate set up.&lt;/p&gt;

&lt;p&gt;The problem comes with the OrderLineState. In our application, we have a separate part of the system which tracks the state of orders. There are two implications of this being a separate concern:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The OrderLineState is not considered part of the Customer aggregate. There’s no relation from the OrderLine to the OrderLineState. &lt;/li&gt;

  &lt;li&gt;The piece of code that creates the initial state object for an OrderLine is logically a long way from the piece of code that creates the OrderLine. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This means that when we create the OrderLineState, we need to explicitly tell NHibernate about the new entity:&lt;/p&gt;

&lt;pre class="c#" name="code"&gt;using (new SessionScope())
{
    var customer = ActiveRecordMediator&amp;lt;Customer&amp;gt;.FindByPrimaryKey(customerId);
    var shoppingOrder = customer.AddOrder(some, parameters);
    var newOrderLine = shoppingOrder.AddLine(some, parameters);

    // In some other part of the system, perhaps responding to a domain event
    var state = new OrderLineState(newOrderLine);
    ActiveRecordMediator&amp;lt;OrderLineState&amp;gt;.Save(state);
}&lt;/pre&gt;

&lt;p&gt;But this code throws an exception from the call to Save(state):&lt;/p&gt;

&lt;pre&gt;NHibernate.PropertyValueException: not-null property references a null or transient valueNHOddities.OrderLine.Parent&lt;/pre&gt;

&lt;p&gt;This makes sense. We’ve asked NHibernate to save the OrderLineState object. This has a non-null, cascading reference to the OrderLine, so it tries to save the OrderLine. Because the relationship OrderLine.Parent (the Order) does not have cascading configured, NHibernate won’t try to save the Order yet. So the Order referenced by OrderLine.Parent is a transient object, and we get the corresponding exception.&lt;/p&gt;

&lt;p&gt;There are a variety of ways to fix this. All of them work, in that they allow the code above to run and make the correct INSERT statements in the database.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Remove the NHibernate NotNull constraint on the OrderLine.Parent property. This lets NHibernate save the OrderLine before it’s saved the order. I don’t like this for two reasons. Firstly, the NotNull constraint reflects a genuine constraint: an OrderLine must always belong to an order. Secondly, that NotNull constraint is probably reflected on the database column definition, so we’d have to change the database schema, removing a meaningful and useful constraint. In general, I don’t like having to change what is a genuine reflection of the domain just to make things convenient for the framework I’m using. &lt;/li&gt;

  &lt;li&gt;Explicitly flush the session after adding the Order and OrderLine to the Customer aggregate, and before saving the new OrderLineState. I don’t like this one either. It requires my domain code to explicitly deal with session management. We usually consider this to be an infrastructural concern. We have a web app, so we handle session and transaction management at the request level. &lt;/li&gt;

  &lt;li&gt;Add a cascade on the BelongsTo relation OrderLine.Parent. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Introducing this bidirectional cascade seems like the best (or at least, least-worst) solution. But it doesn’t quite seem right.&lt;/p&gt;

&lt;h4&gt;Is there anything wrong with a bidirectional cascade?&lt;/h4&gt;

&lt;p&gt;As I discussed earlier, it feels like cascades should run from parents to children, not the other way, and not in both directions. This isn’t written down as a rule or guidance anywhere that I can find in the NHibernate documentation, but it seems to be the standard approach. Indeed when I &lt;a href="http://twitter.com/ascordellis/statuses/3719823862" target="_blank"&gt;tweeted&lt;/a&gt; about this, I got &lt;a href="http://twitter.com/tobinharris/statuses/3720516663" target="_blank"&gt;a reply&lt;/a&gt; from none other than &lt;a href="http://www.tobinharris.com/" target="_blank"&gt;one of the authors&lt;/a&gt; of &lt;a href="http://www.manning.com/kuate/" target="_blank"&gt;NHibernate In Action&lt;/a&gt; himself:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;@&lt;a href="http://twitter.com/ascordellis"&gt;ascordellis&lt;/a&gt; Cascade on both sides feels heavy, are you sure that both sides need to be the big daddy of the relationship?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;For now, I’m leaving it in. For our problem, it’s the least intrusive solution. But I’d love to hear your opinion. Is there a better way to solve our problem? Should NHibernate just deal with it for us?&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2788569112547349568-5219885882571494154?l=alexscordellis.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/alexscordellis/~4/g67ctiarKKI" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://alexscordellis.blogspot.com/feeds/5219885882571494154/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://alexscordellis.blogspot.com/2009/09/nhibernate-bidirectional-cascade-when.html#comment-form" title="3 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/5219885882571494154?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/5219885882571494154?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/alexscordellis/~3/g67ctiarKKI/nhibernate-bidirectional-cascade-when.html" title="NHibernate Bidirectional Cascade – when is it appropriate?" /><author><name>Alex Scordellis</name><uri>http://www.blogger.com/profile/04874376446759200232</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://3.bp.blogspot.com/_xSv6Z4_T9iE/TDyeFksaK2I/AAAAAAAAAJg/AjTKq_entbo/S220/P1030192_2_export.jpg" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh4.ggpht.com/_xSv6Z4_T9iE/SqDQ4C4X9vI/AAAAAAAAAIE/uU8VHrDqloY/s72-c/transient_thumb1.png?imgmax=800" height="72" width="72" /><thr:total>3</thr:total><feedburner:origLink>http://alexscordellis.blogspot.com/2009/09/nhibernate-bidirectional-cascade-when.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DEMNSHo7fCp7ImA9WxJbEk0.&quot;"><id>tag:blogger.com,1999:blog-2788569112547349568.post-7122770776118614290</id><published>2009-07-21T21:01:00.001+01:00</published><updated>2009-07-21T21:01:39.404+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-07-21T21:01:39.404+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="git" /><title>How to recover lost commits in a git repository</title><content type="html">&lt;p&gt;Today we had a problem: we lost several git commits when a rebase went wrong. We’re still not sure how this happened, but we were able to recover the commits. Here’s a quick summary of how we managed that, which I hope will help others get out of similar situations.&lt;/p&gt;  &lt;p&gt;We tried to abort a rebase that had a lot of conflicts, and it took us from a situation like this:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://lh6.ggpht.com/_xSv6Z4_T9iE/SmYeh7U06nI/AAAAAAAAAG4/k0YyW8nqr48/s1600-h/prerebase2.png"&gt;&lt;img title="pre-rebase" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="97" alt="pre-rebase" src="http://lh3.ggpht.com/_xSv6Z4_T9iE/SmYeidM3CtI/AAAAAAAAAG8/pTOS68UtS-w/prerebase_thumb.png?imgmax=800" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;to one like this:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://lh6.ggpht.com/_xSv6Z4_T9iE/SmYeinZF5OI/AAAAAAAAAHA/PVYixA2w5Y8/s1600-h/postrebase5.png"&gt;&lt;img title="post-rebase" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="87" alt="post-rebase" src="http://lh3.ggpht.com/_xSv6Z4_T9iE/SmYejCIoW9I/AAAAAAAAAHE/3eqmiOPGq8k/postrebase_thumb1.png?imgmax=800" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Disaster! Our “last big commit on my story” has vanished! We were pretty sure it was still in the repository somewhere, it just wan't reachable from any named branch. We hunted around in &lt;code&gt;git log&lt;/code&gt;, &lt;code&gt;git fsck&lt;/code&gt; and other commands with no luck. It turns out that the answer lies in &lt;code&gt;git reflog show&lt;/code&gt;&lt;/p&gt;  &lt;pre name="code"&gt;$ git reflog show
3330b4e HEAD@{0}: checkout: moving from ms2 to my-story
3330b4e HEAD@{1}: checkout: moving from 3330b4e0b9af502908ce2c59958ec1e7f83a1a4b to ms2
3330b4e HEAD@{2}: checkout: moving from my-story to 3330b4e
5b50352 HEAD@{3}: rebase: updating HEAD
8f4a119 HEAD@{4}: rebase: more work on my story
c715f09 HEAD@{5}: rebase: some work on my story
6e1441d HEAD@{6}: checkout: moving from my-story to 6e1441d03b200d62f9ffc28d902c60a289d2ea3b^0
5b50352 HEAD@{7}: checkout: moving from mainline to my-story
6e1441d HEAD@{8}: commit: more work by the rest of the team
e72f33f HEAD@{9}: checkout: moving from my-story to mainline
5b50352 HEAD@{10}: commit: last big commit on my story
3330b4e HEAD@{11}: commit: more work on my story
a7d49b0 HEAD@{12}: commit: some work on my story
f3d00fb HEAD@{13}: checkout: moving from master to my-story
f3d00fb HEAD@{14}: checkout: moving from mainline to master
e72f33f HEAD@{15}: commit: some work done by other developers
f3d00fb HEAD@{16}: checkout: moving from master to mainline
f3d00fb HEAD@{17}: commit: commit b
2fcece2 HEAD@{18}: commit (initial): commit a&lt;/pre&gt;

&lt;p&gt;There it is! We now have the SHA for the “last big commit on my story”. We can check that this really is the right one:&lt;/p&gt;

&lt;pre name="code"&gt;$ git show 5b50352

commit 5b503520f132e1a64c510816fcd61cc97626791e
Author: Alex Scordellis &lt;alex.scordellis  @GMAIL.COM&gt;
Date:   Tue Jul 21 20:26:21 2009 +0100

    last big commit on my story

diff --git a/anotherfile.c b/anotherfile.c

  ...diff contents elided...&lt;/pre&gt;

&lt;p&gt;Now all we had to do was reattach a branch name to that SHA, and we were back where we started:&lt;/p&gt;

&lt;pre name="code"&gt;ascordel@ALEXSCORDEL /c/alex/code/git-recovery
$ git checkout 5b50352
Note: moving to '5b50352' which isn't a local branch
If you want to create a new branch from this checkout, you may do so
(now or later) by using -b with the checkout command again. Example:
  git checkout -b &lt;new_branch_name&gt;
HEAD is now at 5b50352... last big commit on my story

ascordel@ALEXSCORDEL /c/alex/code/git-recovery (5b50352...)
$ git checkout -b recovered-my-story
Switched to a new branch 'recovered-my-story'&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://lh5.ggpht.com/_xSv6Z4_T9iE/SmYejcuRweI/AAAAAAAAAHI/oJ6JqmtWFN4/s1600-h/post-fix%5B2%5D.png"&gt;&lt;img title="post-fix" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="85" alt="post-fix" src="http://lh4.ggpht.com/_xSv6Z4_T9iE/SmYej9mKRkI/AAAAAAAAAHM/yHpC8u-YeFg/post-fix_thumb.png?imgmax=800" width="244" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now we’re back where we were at the beginning. We can start again and try to get the rebase through this time. We still don’t know where it went wrong in the first place, but we were pretty relieved to get our work back after a short period of panic!&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2788569112547349568-7122770776118614290?l=alexscordellis.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/alexscordellis/~4/MlxL4nAPxRU" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://alexscordellis.blogspot.com/feeds/7122770776118614290/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://alexscordellis.blogspot.com/2009/07/how-to-recover-lost-commits-in-git.html#comment-form" title="12 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/7122770776118614290?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/7122770776118614290?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/alexscordellis/~3/MlxL4nAPxRU/how-to-recover-lost-commits-in-git.html" title="How to recover lost commits in a git repository" /><author><name>Alex Scordellis</name><uri>http://www.blogger.com/profile/04874376446759200232</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://3.bp.blogspot.com/_xSv6Z4_T9iE/TDyeFksaK2I/AAAAAAAAAJg/AjTKq_entbo/S220/P1030192_2_export.jpg" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh3.ggpht.com/_xSv6Z4_T9iE/SmYeidM3CtI/AAAAAAAAAG8/pTOS68UtS-w/s72-c/prerebase_thumb.png?imgmax=800" height="72" width="72" /><thr:total>12</thr:total><feedburner:origLink>http://alexscordellis.blogspot.com/2009/07/how-to-recover-lost-commits-in-git.html</feedburner:origLink></entry><entry gd:etag="W/&quot;A0YHSXcyeSp7ImA9WxVUGUQ.&quot;"><id>tag:blogger.com,1999:blog-2788569112547349568.post-2403404082768213760</id><published>2009-03-25T16:38:00.001Z</published><updated>2009-03-25T16:38:58.991Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-03-25T16:38:58.991Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Object Oriented Programming" /><category scheme="http://www.blogger.com/atom/ns#" term="Languages" /><category scheme="http://www.blogger.com/atom/ns#" term="Functional Programming" /><category scheme="http://www.blogger.com/atom/ns#" term="NHibernate" /><category scheme="http://www.blogger.com/atom/ns#" term="LINQ" /><title>Problems mixing functional and object-oriented paradigms: NHibernate</title><content type="html">&lt;p&gt;Imagine a typical operation being performed in a regular CRUD business app. In most cases, this will be written in an object-oriented language and will involve mutable objects.&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;grab some objects from the DB &lt;/li&gt;    &lt;li&gt;modify their state according to some business rules &lt;/li&gt;    &lt;li&gt;save the new state back to the DB &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;This pattern, in which an object changes state over time to represent changes in the ‘real world’ that we are modelling, is probably the most prevalent model found in business software systems which use an object-oriented language. Let’s call it the mutable-object pattern.&lt;/p&gt;  &lt;p&gt;On the other hand, if we were to write this operation in a functional programming language, we are likely to do things differently:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;take some data structures as input to the function &lt;/li&gt;    &lt;li&gt;compute the values which result from applying some operation to that data &lt;/li&gt;    &lt;li&gt;return a new set of data structures representing those results &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Crucially, this code written in the functional style does not alter, or mutate, the data values in the input data structures. These structures are typically immutable.&lt;/p&gt;  &lt;p&gt;There’s been some debate recently about how, when and if we can, or even should, mix these two styles. The addition of LINQ to C# has brought a functional paradigm (delayed execution of queries over collections) to an OO language in which most developers are used to the mutable-object pattern, and really brought this issue into the mainstream.&lt;/p&gt;  &lt;p&gt;I think that it’s important to represent each part of your code in the way which most clearly expresses your intention. If your intention is to modify some existing data in a relatively simple way according to some rules, the mutable-object pattern works well. If you need to operate on collections of data structures, performing operations which are more algorithmic in nature, a functional style works well. For example, a SQL query expresses very clearly, using a functional paradigm, what you are trying to achieve. What would you rather read? &lt;code&gt;SELECT MAX(Age) FROM People;&lt;/code&gt; or:&lt;/p&gt;  &lt;pre class="c#" name="code"&gt;max = 0;
foreach (var person in people)
    if(person.Age &amp;gt; max)
        max = person.Age;&lt;/pre&gt;

&lt;p&gt;So there is benefit from mixing the mutable-object and functional styles, but we need to be careful at the boundary between areas of code written in these different styles. I came across a significant example of this &lt;a href="http://twitter.com/ascordellis/status/1376821003" target="_blank"&gt;recently&lt;/a&gt;. NHibernate assumes that you will use the mutable-object style I described at the top of the post. In particular, it expects that there is only one copy in memory of each entity represented by a database row. If it returns you a CLR object in response to a query, it doesn’t let you save a different CLR object back to the same database row. If you want to modify the data in the database, you need to modify the CLR object that NHibernate gave you.&lt;/p&gt;

&lt;p&gt;We shouldn’t really be surprised by this. The boundary between object-oriented programming and relational data storage has &lt;a href="http://blogs.tedneward.com/2006/06/26/The+Vietnam+Of+Computer+Science.aspx" target="_blank"&gt;long provided thorny problems&lt;/a&gt; for software development, because of the natural &lt;a href="http://en.wikipedia.org/wiki/Object-Relational_impedance_mismatch" target="_blank"&gt;impedance mismatch&lt;/a&gt; between OO programming and relational data (ironically, this is exactly the problem that NHibernate does a pretty good job of solving). There’s a similar impedance mismatch between the mutable-object pattern and functional styles involving immutable data structures.&lt;/p&gt;

&lt;h5&gt;Footnote&lt;/h5&gt;

&lt;p&gt;I originally wrote this post using the phrase “the OO paradigm” to describe the mutable-object pattern, until &lt;a href="http://www.chrisleishman.com/" target="_blank"&gt;Chris Leishman&lt;/a&gt; pointed out that using an OO language does not necessarily imply mutability. Mutability is just the typical way that we work with objects in an imperative language like C#. Similarly, I am not asserting that all functional programming involves algorithms consuming immutable objects and churning out new immutable objects, just highlighting one pattern typically found in functional programming.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2788569112547349568-2403404082768213760?l=alexscordellis.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/alexscordellis/~4/gqc0y3_k-CA" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://alexscordellis.blogspot.com/feeds/2403404082768213760/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://alexscordellis.blogspot.com/2009/03/problems-mixing-functional-and-object.html#comment-form" title="7 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/2403404082768213760?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/2403404082768213760?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/alexscordellis/~3/gqc0y3_k-CA/problems-mixing-functional-and-object.html" title="Problems mixing functional and object-oriented paradigms: NHibernate" /><author><name>Alex Scordellis</name><uri>http://www.blogger.com/profile/04874376446759200232</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://3.bp.blogspot.com/_xSv6Z4_T9iE/TDyeFksaK2I/AAAAAAAAAJg/AjTKq_entbo/S220/P1030192_2_export.jpg" /></author><thr:total>7</thr:total><feedburner:origLink>http://alexscordellis.blogspot.com/2009/03/problems-mixing-functional-and-object.html</feedburner:origLink></entry><entry gd:etag="W/&quot;Ak8AQns4fCp7ImA9WxVUFk4.&quot;"><id>tag:blogger.com,1999:blog-2788569112547349568.post-6081395051503696947</id><published>2009-03-21T12:34:00.001Z</published><updated>2009-03-21T12:34:03.534Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-03-21T12:34:03.534Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Gotchas" /><category scheme="http://www.blogger.com/atom/ns#" term="ASP.NET" /><title>ASP.NET doesn’t fire PostRequestHandlerExecute when you Response.Redirect</title><content type="html">&lt;h4&gt;The problem&lt;/h4&gt;  &lt;p&gt;We recently discovered that our application was leaking database transactions. Checking the logs revealed that we were not closing transactions whenever we redirect within the application. &lt;/p&gt;  &lt;h4&gt;The cause&lt;/h4&gt;  &lt;p&gt;We had been closing transactions in the event handler for the &lt;code&gt;PostRequestHandlerExecute&lt;/code&gt; event exposed by &lt;code&gt;HttpApplication&lt;/code&gt;. It turns out that this event is not fired when you call &lt;code&gt;Response.Redirect(newUrl)&lt;/code&gt;. &lt;/p&gt;  &lt;h4&gt;The solution&lt;/h4&gt;  &lt;p&gt;We moved our transaction closing code to the &lt;code&gt;EndRequest&lt;/code&gt; handler. This event does get called, even when you redirect. You can also change your call to &lt;code&gt;Response.Redirect(newUrl, false);&lt;/code&gt;, which causes ASP.NET to execute all the usual events in the HTTP pipeline.&lt;/p&gt;  &lt;h4&gt;The post-mortem&lt;/h4&gt;  &lt;p&gt;The &lt;a href="http://msdn.microsoft.com/en-us/library/system.web.httpapplication.aspx" target="_blank"&gt;MSDN documentation for &lt;code&gt;HttpApplication&lt;/code&gt;&lt;/a&gt; gives you an ordered list of the events that are fired during a request, but does not tell you that you can disrupt the events with a Redirect. The &lt;a href="http://msdn.microsoft.com/en-us/library/a8wa7sdt.aspx" target="_blank"&gt;MSDN documentation for &lt;code&gt;Response.Redirect&lt;/code&gt;&lt;/a&gt; does tell you that you can control “whether execution of the current page should terminate”, but doesn’t tell you what that means. It’s not clear which events will and will not still fire.&lt;/p&gt;  &lt;p&gt;We are using the &lt;a href="http://www.castleproject.org/container/index.html" target="_blank"&gt;Castle.Windsor&lt;/a&gt;/&lt;a href="http://www.castleproject.org/activerecord/" target="_blank"&gt;Castle.ActiveRecord&lt;/a&gt;/&lt;a href="http://www.hibernate.org/343.html" target="_blank"&gt;NHibernate&lt;/a&gt; stack, so we based our application class on the &lt;a href="http://rhino-tools.svn.sourceforge.net/viewvc/rhino-tools/trunk/commons/Rhino.Commons.NHibernate/HttpModules/UnitOfWorkApplication.cs?view=markup" target="_blank"&gt;UnitOfWorkApplication&lt;/a&gt; in &lt;a href="http://www.ayende.com/blog" target="_blank"&gt;Ayende&lt;/a&gt;’s Rhino.Commons library. It uses the &lt;code&gt;PostRequestHandlerExecute&lt;/code&gt; event to close the unit of work after handling a request. A unit of work isn’t quite the same thing as a transaction, so it may be deliberate that the unit of work is not closed on redirect. I’ve posted a message to the &lt;a href="http://groups.google.com/group/rhino-tools-dev/" target="_blank"&gt;Rhino Dev Google group&lt;/a&gt; to find out.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2788569112547349568-6081395051503696947?l=alexscordellis.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/alexscordellis/~4/mN_GuIn94D4" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://alexscordellis.blogspot.com/feeds/6081395051503696947/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://alexscordellis.blogspot.com/2009/03/aspnet-doesnt-fire-postrequesthandlerex.html#comment-form" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/6081395051503696947?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/6081395051503696947?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/alexscordellis/~3/mN_GuIn94D4/aspnet-doesnt-fire-postrequesthandlerex.html" title="ASP.NET doesn’t fire PostRequestHandlerExecute when you Response.Redirect" /><author><name>Alex Scordellis</name><uri>http://www.blogger.com/profile/04874376446759200232</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://3.bp.blogspot.com/_xSv6Z4_T9iE/TDyeFksaK2I/AAAAAAAAAJg/AjTKq_entbo/S220/P1030192_2_export.jpg" /></author><thr:total>2</thr:total><feedburner:origLink>http://alexscordellis.blogspot.com/2009/03/aspnet-doesnt-fire-postrequesthandlerex.html</feedburner:origLink></entry><entry gd:etag="W/&quot;C0QHRnc-fyp7ImA9WxVUE00.&quot;"><id>tag:blogger.com,1999:blog-2788569112547349568.post-9120099089519935328</id><published>2009-03-17T13:39:00.001Z</published><updated>2009-03-17T14:48:57.957Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-03-17T14:48:57.957Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="QCon" /><category scheme="http://www.blogger.com/atom/ns#" term="Conferences" /><title>My day at #QCon</title><content type="html">&lt;p&gt;I spent last Wednesday at &lt;a href="http://qconlondon.com/" target="_blank"&gt;QCon&lt;/a&gt;. It was definitely an interesting day, but I felt like I missed a lot of stuff on other tracks. I also bumped into a few ex-colleagues from my pre-TW days and an old mate from uni who I hadn’t seen in years – I guess enterprise software is a small world…&lt;/p&gt;  &lt;p&gt;First up was &lt;a href="http://en.wikipedia.org/wiki/C._A._R._Hoare" target="_blank"&gt;Sir Tony Hoare&lt;/a&gt;. Not having a background in computer science, I didn’t have quite the same feeling of awe as half the rest of the room. He made a few comparisons between software engineering (pragmatic, seeking dependability, short term view) vs computer science (perfectionist, seeking correctness, long term view), which were largely uncontroversial. Things got a bit interesting towards the end, where he stated his vision: “One day, software will be the most reliable component of every product which contains it … because of the successful interplay of research into the science of programming and the engineering of software”, and then fielded some interesting questions. It emerged that he sees complete specification as the limit of testing. I came away thinking that it’s important to have the computer scientists researching new ways for us to be certain about the behaviour of computer software, and to have the software engineers deciding pragmatically which of those methods are useful, and in what doses. Whether this will ever get us to Sir Tony’s vision, I’m not sure.&lt;/p&gt;  &lt;p&gt;I popped into &lt;a href="http://olabini.com/" target="_blank"&gt;Ola Bini&lt;/a&gt;’s introduction to the emerging languages track, to see him explain why languages are important. My highlight here was Ola’s point that it’s all about communication, and we need to consider the best medium (i.e. language) for communicating each part of our systems to the machine, and to other humans. Since the target of our communication changes, so should the medium, and this is why we need different programming languages.&lt;/p&gt;  &lt;p&gt;Next up, ThoughtWorks’ &lt;a href="http://iansrobinson.com/" target="_blank"&gt;Ian Robinson&lt;/a&gt; on how to start an SOA initiative at enterprise scale. This was my pick of the day. It was one of those talks that makes you consider a whole new approach to an area of your work. I’ve picked out some key messages.&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;We should focus on capabilities which realise outcomes which deliver benefits (the what), rather than on services for services’ sake (the how). This allows us to focus on delivering those capabilities which differentiate our business from our competitors. &lt;/li&gt;    &lt;li&gt;There’s a key difference between who is responsible for a business capability, and who is responsible for keeping a web service up. Engaging those in the first group will help engender a sense of ownership and urgency and ultimately lead us to more value-driven systems. For example, Ian suggests Responsibility Focused Stories (as &amp;lt;role&amp;gt;, I am responsible for &amp;lt;outcome&amp;gt;, which delivers &amp;lt;benefit&amp;gt;) to help identify these people and their responsibilities. From my own recent experience, I can attest that getting these business capability owners involved is often a significant challenge, particularly inside large companies, and I hope to use Ian’s ideas to help me do this. &lt;/li&gt;    &lt;li&gt;Different service implementations are needed for different business capabilities, even if they operate on the same data. Don’t always assume that your business entities will take the same form and live in the same services. In particular the way we use and represent an entity may change significantly over the lifetime of that entity (consider the different capabilities involved in signing up a new customer, and performing daily financial trades on behalf of that customer). &lt;font color="#ff0000"&gt;&lt;strong&gt;Update:&lt;/strong&gt;&lt;/font&gt; see comment from Ian below for a clarification. &lt;/li&gt;    &lt;li&gt;Use &lt;a href="http://www.infoq.com/articles/consumer-driven-contracts" target="_blank"&gt;consumer-driven contracts&lt;/a&gt; to reduce coupling between service providers and consumers. &lt;/li&gt;    &lt;li&gt;Have long-lived capability delivery teams responsible for business capabilities, but augment them with additional resources and knowledge from new projects that are taking advantage of the capabilities. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;After lunch I was back in Ola’s track for &lt;a href="http://jonasboner.com/"&gt;Jonas Bonér&lt;/a&gt; on real-world Scala. He showed a simple chat application using the Lift framework, and whistled through a few of Scala’s more unusual constructs. Overall, I wasn’t convinced by what would make me choose Scala over any other functional programming language – it largely resembled Java with a few extra constructs thrown in. I think Jonas missed an opportunity to demonstrate the practical benefits that these constructs could bring and so get people excited it.&lt;/p&gt;  &lt;p&gt;I then decided to go to &lt;a href="http://www.michaelfeathers.com/" target="_blank"&gt;Michael Feathers&lt;/a&gt; and &lt;a href="http://www.m3p.co.uk/blog" target="_blank"&gt;Steve Freeman&lt;/a&gt; talk about the history of TDD. Having written and co-written &lt;a href="http://www.amazon.co.uk/Working-Effectively-Legacy-Robert-Martin/dp/0131177052" target="_blank"&gt;Working Effectively with Legacy Code&lt;/a&gt; and &lt;a href="http://www.jmock.org/oopsla2004.pdf" target="_blank"&gt;Mock Roles, Not Objects&lt;/a&gt; respectively, I have a lot of respect for these guys.&amp;#160; Those texts played key roles in my understanding of good OO design. The session was an interesting history lesson, a useful reminder of the core principles, and contained a few nice anecdotes. I was particularly tickled by the fact that early practitioners of testing (Gerry Weinberg, Kent Beck) just assumed that everyone else was doing testing too, as they considered it to be part of doing a professional job. Plus ça change.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.martinfowler.com/" target="_blank"&gt;Martin Fowler&lt;/a&gt; then described our experiences with Ruby projects at ThoughtWorks over the last few years. It was good to see some statistics backing up the idea that Ruby works in the enterprise. 36 of the 41 projects ThoughtWorks has undertaken in Ruby would use it again, and of those 5 that wouldn’t, 4 said that the reason was due to the problems getting people to adapt to Ruby, rather than Ruby’s ability to perform the job required. An amusing anecdote midway through: developers on a Ruby project estimated their productivity boost (over, say, Java) as 2-5x in earlier parts of the project, reducing to 1.5x in later parts, but jumping back up to 2-3x when they had to go back to Java and remembered just how bad it was! Martin’s a great speaker, so as always it was an entertaining session.&lt;/p&gt;  &lt;p&gt;In conclusion, I enjoyed all the sessions and heard some interesting things. But the biggest lesson I’ll take away is to go to talks about things I don’t know about, not things I do. I’m sure I’d have learnt a lot more new ideas in Rich Hickey’s Clojure presentation than in Michael and Steve’s TDD history. Not through any fault of Michael and Steve (and I certainly don’t want to pick on them), but because I’ve read a lot of that stuff before. There were also a number of talks on web architecture and RESTful services that I’d like to have caught. I also wish I’d taken notes in more of the sessions; as well as helping me take more of the information on board it would have helped me writing this post!&lt;/p&gt;  &lt;p&gt;For those who couldn’t make it (and others like me who want to catch up on sessions they missed), all of the slides are on the &lt;a href="http://qconlondon.com/london-2009/schedule/wednesday.jsp" target="_blank"&gt;QCon site&lt;/a&gt;, although some may need an attendee-only password. &lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2788569112547349568-9120099089519935328?l=alexscordellis.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/alexscordellis/~4/eUeoN9TaEmI" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://alexscordellis.blogspot.com/feeds/9120099089519935328/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://alexscordellis.blogspot.com/2009/03/my-day-at-qcon.html#comment-form" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/9120099089519935328?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/9120099089519935328?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/alexscordellis/~3/eUeoN9TaEmI/my-day-at-qcon.html" title="My day at #QCon" /><author><name>Alex Scordellis</name><uri>http://www.blogger.com/profile/04874376446759200232</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://3.bp.blogspot.com/_xSv6Z4_T9iE/TDyeFksaK2I/AAAAAAAAAJg/AjTKq_entbo/S220/P1030192_2_export.jpg" /></author><thr:total>1</thr:total><feedburner:origLink>http://alexscordellis.blogspot.com/2009/03/my-day-at-qcon.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CU8FRXszfCp7ImA9WxVSFU8.&quot;"><id>tag:blogger.com,1999:blog-2788569112547349568.post-2858515171989187230</id><published>2009-01-09T17:56:00.001Z</published><updated>2009-01-09T17:56:54.584Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-01-09T17:56:54.584Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Functional Programming" /><category scheme="http://www.blogger.com/atom/ns#" term="LINQ" /><title>LINQ with side effects: convenient but dangerous</title><content type="html">&lt;p&gt;Consider the following C# code. It’s trying to make sure that a Record exists for a given Thing, either by finding an existing Record or by creating a new one.&lt;/p&gt;  &lt;pre class="c#" name="code"&gt;        public Record FindOrCreateRecordFor(Thing thing)
        {
            var recordFinders = new Func&amp;lt;Thing, Record&amp;gt;[]
                {
                    thing =&amp;gt; retrieveExistingRecordFor(thing),
                    thing =&amp;gt; createNewRecordFor(thing)
                };
            return recordFinders.Select(f =&amp;gt; f(thing)).First(record =&amp;gt; record.Exists);
        }&lt;/pre&gt;

&lt;p&gt;What happens if retrieveExistingRecordFor(thing) returns a record which has Exists == true? The answer, thanks to deferred query execution, is that createNewRecordFor(thing) is &lt;strong&gt;not&lt;/strong&gt; called. &lt;/p&gt;

&lt;p&gt;This is probably important to the correct functioning of our system; we don’t want to create a second, duplicate, Record for any one Thing. Because it’s important, it should be obvious from the code, and I’d argue that it probably isn’t. To someone used to imperative programming styles (which covers most C# programmers, certainly including me), it looks at first glance like both retrieveExistingRecordFor(thing) and createNewRecordFor(thing) will be called, then we’ll return the first result that has Exists == true.&lt;/p&gt;

&lt;p&gt;[ By the way, if you don’t understand why createRecordFor(thing) is not called, you should read Jon Skeet’s &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2008/02/14/human-linq.aspx" target="_blank"&gt;Human LINQ&lt;/a&gt; post. For maximum effect, you should go to one of his talks and see it live, but reading about it is the next best thing. ]&lt;/p&gt;

&lt;p&gt;What alternatives do we have in C#? We could write out the chain of alternatives explicitly:&lt;/p&gt;

&lt;pre class="c#" name="code"&gt;        public Record FindOrCreateRecordFor(Thing thing)
        {
            var record = retrieveKnownRecordFor(thing);
            if (!record.Exists)
                record = createNewRecordFor(thing);
            return record;
        }&lt;/pre&gt;

&lt;p&gt;That's not too bad when there are two alternatives. In the example from my project that inspired this blog post, there were three, and I didn’t want to write a three-deep nested if. It also hardcodes the sequence of finder objects, which prevents you from doing any runtime configuration.&lt;/p&gt;

&lt;p&gt;We could use an explicit foreach loop:&lt;/p&gt;

&lt;pre class="c#" name="code"&gt;             foreach (var recordFinder in recordFinders)
             {
                 var candidateRecord = recordFinder(thing);
                 if (candidateRecord.Exists)
                     return candidateRecord;
             }&lt;/pre&gt;

&lt;p&gt;This is probably the best option, and the one I’ve ended up taking in our codebase. But I’m still not completely happy. I feel that there should be a better way. I can’t believe that you would write that code in a functional language, or even if you were writing in Ruby with a functional mindset. So if you are familiar with functional coding techniques, I have questions for you: How would you do this? Is it obvious to a functional programmer that this code is right?&lt;/p&gt;

&lt;pre class="c#" name="code"&gt;    return recordFinders.Select(f =&amp;gt; f(thing)).First(record =&amp;gt; record.Exists);&lt;/pre&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2788569112547349568-2858515171989187230?l=alexscordellis.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/alexscordellis/~4/QrHr4XCqexU" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://alexscordellis.blogspot.com/feeds/2858515171989187230/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://alexscordellis.blogspot.com/2009/01/linq-with-side-effects-convenient-but.html#comment-form" title="4 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/2858515171989187230?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/2858515171989187230?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/alexscordellis/~3/QrHr4XCqexU/linq-with-side-effects-convenient-but.html" title="LINQ with side effects: convenient but dangerous" /><author><name>Alex Scordellis</name><uri>http://www.blogger.com/profile/04874376446759200232</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://3.bp.blogspot.com/_xSv6Z4_T9iE/TDyeFksaK2I/AAAAAAAAAJg/AjTKq_entbo/S220/P1030192_2_export.jpg" /></author><thr:total>4</thr:total><feedburner:origLink>http://alexscordellis.blogspot.com/2009/01/linq-with-side-effects-convenient-but.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CU8HRHo8fyp7ImA9WxVTEEg.&quot;"><id>tag:blogger.com,1999:blog-2788569112547349568.post-5850576810792890848</id><published>2008-12-23T17:34:00.001Z</published><updated>2008-12-23T17:37:15.477Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-12-23T17:37:15.477Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="mocks" /><category scheme="http://www.blogger.com/atom/ns#" term="Lessons Learned" /><category scheme="http://www.blogger.com/atom/ns#" term="testing" /><title>Don't always use a mock</title><content type="html">It's easy to get carried away with mocking, especially when we have great frameworks like &lt;a href="http://ayende.com/projects/rhino-mocks.aspx" target="_blank"&gt;Rhino Mocks&lt;/a&gt; and &lt;a href="http://code.google.com/p/mockito/" target="_blank"&gt;Mockito&lt;/a&gt; helping us. I've definitely been guilty of it in the past, and I almost fell down that trap again last week. I had a method which needed to do three separate pieces of work in three separate transactions. It looked a bit like this:   &lt;pre class="c#" name="code"&gt;    void Synchronise()
    {
        using (transactionService.LocalTransaction())
        {
            otherObject.OperationA();
        }

        using (transactionService.LocalTransaction())
        {
            otherObject.OperationB();
        }

        using (transactionService.LocalTransaction())
        {
            otherObject.OperationC();
        }
    }&lt;/pre&gt;
I wanted to verify that each of the three operations occurred in separate transactions. It took me half an hour of frustration trying to accomplish this with Rhino.Mocks. I couldn't work out how to return three different transaction objects from the mock transactionService, and verify which of them was open during each mock call to otherObject. Then I took a step back, remembered that we don't have to use mocks for everything, and wrote the following classes: 

&lt;pre class="c#" name="code"&gt;public class FakeTransaction : IDisposable
{
    public bool InTransaction = true;

    public void Dispose()
    {
        InTransaction = false;
    }
}

public class FakeTransactionService : ITransactionService
{
    public readonly List&amp;lt;FakeTransaction&amp;gt; Transactions = new List&amp;lt;FakeTransaction&amp;gt;();

    public IDisposable LocalTransaction()
    {
        Transactions.Add(new FakeTransaction());
        return Transactions.Last();
    }
}&lt;/pre&gt;
Now I can write tests like this: 

&lt;pre class="C#" name="code"&gt;otherObject
	.Stub(t =&amp;gt; t.OperationA())
	.WhenCalled(invocation =&amp;gt;
	{
		Assert.That(transactionService.Transactions.Count(), Is.EqualTo(1));
		Assert.That(transactionService.Transactions.First().InTransaction, Is.True);
	});
	
otherObject
	.Stub(t =&amp;gt; t.OperationB())
	.WhenCalled(invocation =&amp;gt;
	{
		Assert.That(transactionService.Transactions.Count(), Is.EqualTo(2));
		Assert.That(transactionService.Transactions.First().InTransaction, Is.False);
		Assert.That(transactionService.Transactions.ElementAt(1).InTransaction, Is.True);
	});&lt;/pre&gt;

&lt;p&gt;Much better! Especially when I added some nice helper methods to FakeTransactionService to do all the asserts in one line:&lt;/p&gt;

&lt;pre class="C#" name="code"&gt;WhenCalled(invocation =&amp;gt; Assert.That(transactionService.IsInTransaction(2)))&lt;/pre&gt;

&lt;p&gt;Again, this isn't a criticism of &lt;a href="http://ayende.com/projects/rhino-mocks.aspx" target="_blank"&gt;Rhino Mocks&lt;/a&gt;, which is another excellent tool, but a reminder that we shouldn't get bound to a particular tool, and always keep an open mind to alternatives. In general, this also echoes the idea that we should focus on the problem (verifying that each stage occurred in a separate transaction) rather than the solution (how to accomplish that in &lt;a href="http://ayende.com/projects/rhino-mocks.aspx" target="_blank"&gt;Rhino Mocks&lt;/a&gt;).&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2788569112547349568-5850576810792890848?l=alexscordellis.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/alexscordellis/~4/4PQSFnZCTI4" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://alexscordellis.blogspot.com/feeds/5850576810792890848/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://alexscordellis.blogspot.com/2008/12/don-always-use-mock.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/5850576810792890848?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/5850576810792890848?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/alexscordellis/~3/4PQSFnZCTI4/don-always-use-mock.html" title="Don&amp;#39;t always use a mock" /><author><name>Alex Scordellis</name><uri>http://www.blogger.com/profile/04874376446759200232</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://3.bp.blogspot.com/_xSv6Z4_T9iE/TDyeFksaK2I/AAAAAAAAAJg/AjTKq_entbo/S220/P1030192_2_export.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://alexscordellis.blogspot.com/2008/12/don-always-use-mock.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CUEAQHs7cCp7ImA9WxVTEE4.&quot;"><id>tag:blogger.com,1999:blog-2788569112547349568.post-2393700529983987457</id><published>2008-12-23T11:58:00.001Z</published><updated>2008-12-23T12:00:41.508Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-12-23T12:00:41.508Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="SQLite" /><category scheme="http://www.blogger.com/atom/ns#" term="Leaky Abstractions" /><category scheme="http://www.blogger.com/atom/ns#" term="Gotchas" /><category scheme="http://www.blogger.com/atom/ns#" term="NHibernate" /><category scheme="http://www.blogger.com/atom/ns#" term="Lessons Learned" /><category scheme="http://www.blogger.com/atom/ns#" term="testing" /><category scheme="http://www.blogger.com/atom/ns#" term="Castle.ActiveRecord" /><title>Using SQLite for fast database testing – technical gotchas and wider lessons learned</title><content type="html">&lt;p&gt;On my current project, we’re successfully using &lt;a href="http://www.sqlite.org/" target="_blank"&gt;SQLite&lt;/a&gt; for in-memory testing with &lt;a href="http://www.hibernate.org/343.html" target="_blank"&gt;NHibernate&lt;/a&gt; / &lt;a href="http://www.castleproject.org/activerecord/index.html" target="_blank"&gt;Castle.ActiveRecord&lt;/a&gt;. This makes tests that run against the database a lot faster than if we ran them against SQL Server.&lt;/p&gt;  &lt;p&gt;NHibernate’s pluggable driver / connection provider model makes this fairly painless, but there are a few gotchas in the technical details that are worth calling out. A couple of these led me to some general observations, neither of which are new but both of which are important.&lt;/p&gt;  &lt;h4&gt;Database lifetimes&lt;/h4&gt;  &lt;p&gt;An in-memory SQLite database lives for the lifetime of the connection, so each time you close and re-open the database, you lose your table structure and your data. Usually NHibernate opens and closes connections as it sees fit so you need to provide a custom DriverConnectionProvider for NHibernate which holds the connection open until you explicitly close it. This has been covered pretty well by &lt;a href="http://notepad2.wordpress.com/2008/05/19/unit-testing-castle-active-record-using-sqlite-in-memory-database/" target="_blank"&gt;other&lt;/a&gt;&amp;#160;&lt;a href="http://brian.genisio.org/2008/07/active-record-mock-framework.html" target="_blank"&gt;bloggers&lt;/a&gt; so I won’t go into details here. Just don’t forget to explicitly close the connection otherwise you’ll keep lots of databases hanging around taking up your memory.&lt;/p&gt;  &lt;h4&gt;The SqlType argument of the Property attribute&lt;/h4&gt;  &lt;p&gt;When we need to override NHibernate’s default choice of data type for a column, we can use the SqlType argument like so:&lt;/p&gt;  &lt;pre class="c#" name="code"&gt;        [Property(ColumnType = &amp;quot;BinaryBlob&amp;quot;, SqlType = &amp;quot;varbinary(max)&amp;quot;)]
        public byte[] Data { get; set; }&lt;/pre&gt;

&lt;p&gt;There’s a problem here – varbinary(max) is a SQL Server column type that isn’t valid in SQLite. SQLite has the BLOB column type for binary data like this. We’d like to be able to pick a different SqlType for production (SQL Server) and test (SQLite) builds. However because SqlType is in an attribute declaration, it has to be a compile time constant. I found that the simplest way around this was to hook into the ActiveRecord initialization pipeline to modify the ActiveRecord metadata before the schema gets created.&lt;/p&gt;

&lt;pre class="c#" name="code"&gt;        [TestFixtureSetUp]
        public virtual void TestFixtureSetUp()
        {
            ActiveRecordStarter.ResetInitializationFlag();
            ActiveRecordStarter.ModelCreated += ActiveRecordStarter_ModelCreated;
            ActiveRecordStarter.Initialize(typeof (MyEntity).Assembly, ActiveRecordSectionHandler.Instance);
        }

        private static void ActiveRecordStarter_ModelCreated(ActiveRecordModel model, IConfigurationSource source)
        {
            if (source.GetConfiguration(typeof (ActiveRecordBase))
                .Children
                .Single(configuration =&amp;gt; configuration.Name == &amp;quot;connection.driver_class&amp;quot;)
                .Value.ToLower().Contains(&amp;quot;sqlite&amp;quot;))
                foreach (var property in model.Properties)
                    if (!string.IsNullOrEmpty(property.PropertyAtt.SqlType) &amp;amp;&amp;amp; property.PropertyAtt.SqlType.ToLower().Contains(&amp;quot;varbinary&amp;quot;))
                        property.PropertyAtt.SqlType = &amp;quot;BLOB&amp;quot;;
        }&lt;/pre&gt;

&lt;h4&gt;Column types and the law of leaky abstractions&lt;/h4&gt;

&lt;p&gt;SQLite and SQL Server offer different sets of column types. For example, SQLite has a TEXT column type for all textual data, whereas SQL Server has fixed and variable length text datatypes like NCHAR(100) and NVARCHAR(MAX). NHibernate and ActiveRecord hide these differences from you. You provide a property declaration and it generates the appropriate DDL for the database which you’ve configured NHibernate to use. For example, here are excerpts from the creation scripts for my current project. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;For SQLite&lt;/strong&gt;&lt;/p&gt;

&lt;pre class="sql" name="code"&gt;create table ErrorLogs (
  Id INTEGER not null,
  RequestUrl TEXT,
  Message TEXT,
  primary key (Id)
)&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;For SQL Server&lt;/strong&gt;&lt;/p&gt;

&lt;pre class="sql" name="code"&gt;create table ErrorLogs (
  Id INTEGER not null,
  RequestUrl NVARCHAR(255) null,
  Message NVARCHAR(255) null,
  primary key (Id)
)&lt;/pre&gt;

&lt;p&gt;Notice the different datatypes and nullability declarations between the two databases. This starts to matter when you write a test that you can insert a really long (&amp;gt; 255 characters) string into the Message column. Your test passes fine against SQLite, then you run your app against SQL Server and it falls over horribly. &lt;/p&gt;

&lt;p&gt;We can fix this example by making individual tests run against SQL Server, then override the default column types in the ActiveRecord attributes to make them pass.&lt;/p&gt;

&lt;pre class="c#" name="code"&gt;        [Test]
        public void should_save_error_log_with_long_message()
        {
            using (SqlServer)
            {
                var moreThan255Chars =
                    &amp;quot;a really really long message a really really long message a really really long message a really really long message a really really long message a really really long message a really really long message a really really long message a really really long message a really really long message &amp;quot;;
                var savedErrorLog = new ErrorLog
                                        {
                                            Message = moreThan255Chars
                                        };

                systemUnderTest.Save(savedErrorLog);

                Flush();

                var retrievedErrorLog = systemUnderTest.Load(savedErrorLog.Id);

                Assert.That(retrievedErrorLog.Message, Is.EqualTo(moreThan255Chars));
            }
        }

        // In a base class of your test fixture class
        protected IDisposable SqlServer
        {
            get
            {
                // Reconfigure NH to use SQLServer
                // Rebuild empty schema
                // DisposableAction invokes the delegate you give 
                // it when it's disposed (inspired by Rhino.Commons)
                return new DisposableAction(TestFixtureSetUp);
            }
        }

        // In the affected ActiveRecord class
        [Property(ColumnType = &amp;quot;StringClob&amp;quot;, SqlType = &amp;quot;NTEXT&amp;quot;)]
        public string Message { get; set; }&lt;/pre&gt;

&lt;p&gt;But this is another example of a situation where we have to remember each time we need to test a field like this, and if we forget, we may well introduce a bug. As I said &lt;a href="http://alexscordellis.blogspot.com/2008/12/html-escaping-in-aspnet-mvc.html" target="_blank"&gt;yesterday&lt;/a&gt;, it’s much better to make it easy to do the right thing, so we should make sure that our automated build will expose significant differences between SQL Server and SQLite automatically. Unfortunately, it seems that the only real option is to run all the tests again against SQL Server. This undoes the reduction in build time that we gained by using SQLite. I think a compromise is to run SQLite tests on the developers’ desktops and run SQL Server tests on the build server.&lt;/p&gt;

&lt;p&gt;This scenario serves up a couple of interesting lessons:&lt;/p&gt;

&lt;h4&gt;Lesson 1: The Law of Leaky Abstractions&lt;/h4&gt;

&lt;p&gt;NHibernate would like you to think that it’s successfully abstracted away the differences in column types and SQL Syntax between the SQL Server and SQLite, but sometimes you need to know what’s behind the façade. This is a classic example of Joel’s &lt;a href="http://www.joelonsoftware.com/articles/LeakyAbstractions.html" target="_blank"&gt;Law of Leaky Abstractions&lt;/a&gt;. NHibernate and ActiveRecord have several leaks in their abstractions, as recently my colleague Stuart &lt;a href="http://no-new-ideas.blogspot.com/2008/11/activerecord-lessons-learnt-1-never.html" target="_blank"&gt;recently pointed out&lt;/a&gt;. They make you feel that you don’t need to worry about the presence of a relational database, but every now and then you need to remember that there is some SQL happening under the hood – in particular around &lt;a href="http://www.google.co.uk/search?q=nhibernate+sessions" target="_blank"&gt;session management&lt;/a&gt; and &lt;a href="http://no-new-ideas.blogspot.com/2008/11/activerecord-lessons-learnt-2-use-lazy.html" target="_blank"&gt;lazy-loading&lt;/a&gt;. This isn’t a criticism of ActiveRecord – it’s a great tool and they do explicitly call out some of these leaks on the &lt;a href="http://www.castleproject.org/activerecord/" target="_blank"&gt;project homepage&lt;/a&gt;.&lt;/p&gt;

&lt;h4&gt;Lesson 2: Every difference between your test and production environments will trip you up at some point&lt;/h4&gt;

&lt;p&gt;I think the headline speaks for itself. In this example, it was the difference between SQL Server and SQLite. This can happen in many areas – it’s not only differences in the technical environment, but differences in datasets and usage patterns can hit you too:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Testing and developing against tiny datasets, so you don’t notice the fact that your app is dog slow with a realistic dataset. &lt;/li&gt;

  &lt;li&gt;Forgetting that, unlike in development, the users’ browsers aren’t on the same machine, or even the same continent, as the web server, so maybe that really chatty AJAX UI isn’t the best plan. &lt;/li&gt;

  &lt;li&gt;Viewing the UI on the 1920*1080 mega-displays that the developers have, and forgetting that the user with a 1024*768 can’t see the navigation links without scrolling sideways. &lt;/li&gt;

  &lt;li&gt;Testing and developing against tiny datasets, so you don’t realise that you haven’t offered the users any easy way to find their data. &lt;a href="http://www.lixo.org/archives/2008/11/27/balances-between-agile-and-usability/" target="_blank"&gt;Carlos puts it better than I can&lt;/a&gt;: &lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;Next time you see a system where there are enormous listings of items with no search, pagination or sorting, ask the developers if they have ever watched a typical user at work; chances are they have only thought about the system as they see it: since the testing dataset is usually small, a loop spitting out a bit of HTML for each element isn’t such a big deal. They might even say there’s a story to implement all that lovely stuff later on, but they just get moved over and over to the bottom of the backlog barrel… until everyone watches a person struggle to find needles in a tabular haystack all day. This is a simple example – almost too trivial actually, but one I’ve seen happen way too many times. &lt;/blockquote&gt;

&lt;p&gt;What do we do about this? On the technical side, we can work to make our development and testing environments as close to production as possible. For the other areas, it’s vital that we are vigilant and keep an eye out for these risks as we go along. To paraphrase Thomas Jefferson: “the price of Agile (not having to write stacks of functional and non-functional specifications at the start of the project) is eternal vigilance (having to keep an eye on all these things as we go along)”.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2788569112547349568-2393700529983987457?l=alexscordellis.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/alexscordellis/~4/PM26xHpbiv0" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://alexscordellis.blogspot.com/feeds/2393700529983987457/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://alexscordellis.blogspot.com/2008/12/using-sqlite-for-fast-database-testing.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/2393700529983987457?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/2393700529983987457?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/alexscordellis/~3/PM26xHpbiv0/using-sqlite-for-fast-database-testing.html" title="Using SQLite for fast database testing – technical gotchas and wider lessons learned" /><author><name>Alex Scordellis</name><uri>http://www.blogger.com/profile/04874376446759200232</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://3.bp.blogspot.com/_xSv6Z4_T9iE/TDyeFksaK2I/AAAAAAAAAJg/AjTKq_entbo/S220/P1030192_2_export.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://alexscordellis.blogspot.com/2008/12/using-sqlite-for-fast-database-testing.html</feedburner:origLink></entry><entry gd:etag="W/&quot;C0QFSH8-fSp7ImA9WxRaGUs.&quot;"><id>tag:blogger.com,1999:blog-2788569112547349568.post-5428262016702081418</id><published>2008-12-22T15:37:00.002Z</published><updated>2008-12-22T15:55:19.155Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-12-22T15:55:19.155Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Security" /><category scheme="http://www.blogger.com/atom/ns#" term="ASP.NET MVC" /><category scheme="http://www.blogger.com/atom/ns#" term="ASPX" /><category scheme="http://www.blogger.com/atom/ns#" term="HTML encoding" /><title>HTML escaping in ASP.NET MVC</title><content type="html">&lt;p&gt;HTML escaping is a key part of web site security, mainly to prevent &lt;a href="http://en.wikipedia.org/wiki/Cross-site_scripting" target="_blank"&gt;Cross-Site Scripting (XSS)&lt;/a&gt; attacks. I’m no security expert, but I do know that everything the user types in must be HTML escaped before rendering it in the browser, otherwise bad people could do nasty things like write javascript which steals all the users cookies.&lt;/p&gt;  &lt;p&gt;HTML escaping isn’t hard to do. You just convert &amp;lt; into &amp;amp;lt; and a few other conversions. .NET provides a very simple way to do it:&lt;/p&gt;  &lt;pre class="c#" name="code"&gt;    var encodedContent = HttpUtility.HtmlEncode(userEnteredContent);&lt;/pre&gt;

&lt;p&gt;ASP.NET MVC makes it pretty easy too:&lt;/p&gt;

&lt;pre class="html" name="code"&gt;&amp;lt;p&amp;gt;
    &amp;lt;%= Html.Encode(ViewData.Model.UserEnteredContent) %&amp;gt;
&amp;lt;/p&amp;gt;&lt;/pre&gt;

&lt;p&gt;But the tricky bit is remembering to do it &lt;strong&gt;every single time&lt;/strong&gt;. If we forget in once place in the whole app, we’ve introduced a security hole. It’s also pretty hard to test automatically that we’ve covered every possible instance – we could write a test for each part of the markup that we know contains user-entered content, but we’re just as likely to miss a test as to miss a call to Html.Encode(). Plus, it would be pretty boring and time-consuming.&lt;/p&gt;

&lt;p&gt;I’m very much a fan of making it easier to do the right thing than to do the wrong thing. On my current project, we decided to look for ways to make HTML escaping happen automatically. This way, we’d be secure by default, and have to explicitly mark out those parts where we want to allow HTML in user content (e.g. if we had a facility where users could enter HTML formatted comments). We discussed a few options.&lt;/p&gt;

&lt;h4&gt;Encoding on the way in&lt;/h4&gt;

&lt;p&gt;We could choose to encode the user’s data on the way in, and store it in the database in escaped form. This could be implemented using a filter, or with some code in Global.asax.cs. However, this feels wrong, for a few reasons:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;HTML encoding is a rendering problem, so the solution should be in rendering. &lt;/li&gt;

  &lt;li&gt;We aren’t storing the data as the user intended it, possibly reducing our options for using this data in the future (e.g. consumption by non-HTML fronted systems). &lt;/li&gt;

  &lt;li&gt;If you’ve encoded on the way in, you mustn’t then encode on the way out. Otherwise you will double encode and the user will see all sorts of HTML entities like &amp;amp;gt; when they typed &amp;gt;. Many ASP.NET MVC helper controls (e.g. &amp;lt;%= Html.ActionLink(ViewData.SomethingTheUserEntered, &amp;quot;action&amp;quot;, &amp;quot;controller&amp;quot;) %&amp;gt;) escape the text you pass them, so you’d have to rewrite all the helpers without the encoding. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;There’s a longer thread about the rights and wrongs of encoding on the way in on the &lt;a href="http://forums.asp.net/t/1194407.aspx" target="_blank"&gt;MSDN forums&lt;/a&gt;. At the moment, I’m firmly in the wrong camp.&lt;/p&gt;

&lt;h4&gt;Encoding on the way out&lt;/h4&gt;

&lt;p&gt;Having decided not to encode on the way in, we considered two ways to make encoding happen by default.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Between the Controller and the View: Use a filter to encode all strings in the ViewData object passed from the controller to the view &lt;/li&gt;

  &lt;li&gt;In the View: Make the &amp;lt;%= %&amp;gt; syntax automagically do HTML escaping. Oh, but don’t do it when I’m generating tags, as in &amp;lt;%= Html.ActionLink(…) %&amp;gt; &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Option 1 is fiddly and imperfect. I wrote a filter to examine the contents of the ViewData dictionary and the ViewData.Model, using reflection to search for read-write properties of type string, and replace their value with the encoded version. Not only is this very fiddly (think of all the recursive reflection), particularly when it comes to collections, but it can’t encode read-only properties or methods on the objects passed to the view. In hindsight, I shouldn’t be surprised that this is difficult – like encoding on the way in, this is a reponsibility being executed in the wrong place. This is a view concern and belongs in the view.&lt;/p&gt;

&lt;p&gt;Option 2 isn’t trivial either – we need to hook into the ASP.NET compiler architecture to override &amp;lt;%= %&amp;gt; and need to find a way not to escape genuine HTML generated inside &amp;lt;%= %&amp;gt;. Fortunately we found &lt;a href="http://blog.codeville.net/2007/12/19/aspnet-mvc-prevent-xss-with-automatic-html-encoding/" target="_blank"&gt;Steve Sanderson’s blog post&lt;/a&gt; (good find Muhammad!) with a working solution.&lt;/p&gt;

&lt;p&gt;Steve’s post is about a year old, which in ASP.NET MVC terms is positively ancient (Preview 2?), so it’s no longer the MVC toolkit that generates HTML, but the HtmlHelper class at the core of MVC. I didn’t fancy rewriting all of the MVC HTML generators (it was tedious enough going through the codebase removing Html.Encode(…)), so for now our views explicitly cast to Steve’s RawHtml class when necessary:&lt;/p&gt;

&lt;pre class="html" name="code"&gt;&amp;lt;span id=&amp;quot;home&amp;quot;&amp;gt;
    &amp;lt;%= (RawHtml) Html.ActionLink(ViewData.Model.SomeUserEnteredContent, &amp;quot;action&amp;quot;, &amp;quot;controller&amp;quot;) %&amp;gt;    
    &amp;lt;%= ViewData.Model.SomeOtherUserEnteredContent %&amp;gt;    
&amp;lt;/span&amp;gt;    &lt;/pre&gt;

&lt;p&gt;SomeUserEnteredContent will be encoded by Html.ActionLink, and SomeOtherUserEnteredContent will be encoded by &amp;lt;%= %&amp;gt;. The &amp;lt;a&amp;gt; tag emitted by Html.ActionLink will not be encoded.&lt;/p&gt;

&lt;h4&gt;&lt;/h4&gt;

&lt;h4&gt;Other Options&lt;/h4&gt;

&lt;p&gt;We also considered the possibility that HTML encoding could be a domain concern. In my opinion, this could be the case for an application that was heavy on user-entered marked-up text, such as a blog engine or an issue tracker where all the text fields are Textile formatted. Then each different field knows whether to allow HTML markup through, and if so, which HTML tags are considered safe, and this is part of the domain model of the application.&lt;/p&gt;

&lt;h4&gt;Conclusion&lt;/h4&gt;

&lt;p&gt;This seems like the most efficient way to make it easy to do the right thing. I’d be very interested to hear any other views, especially if you think this is not the right thing to do.&lt;/p&gt;

&lt;p&gt;Finally, I’m surprised by how little coverage this has received within the ASP.NET MVC community and example code that you see out there on the web. Both that &lt;a href="http://forums.asp.net/t/1194407.aspx" target="_blank"&gt;forum thread&lt;/a&gt; and &lt;a href="http://blog.codeville.net/2007/12/19/aspnet-mvc-prevent-xss-with-automatic-html-encoding/" target="_blank"&gt;Steve’s blog post&lt;/a&gt; date back a year. It is just assumed that everyone knows about this?&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2788569112547349568-5428262016702081418?l=alexscordellis.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/alexscordellis/~4/Opp_eN8nusk" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://alexscordellis.blogspot.com/feeds/5428262016702081418/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://alexscordellis.blogspot.com/2008/12/html-escaping-in-aspnet-mvc.html#comment-form" title="5 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/5428262016702081418?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/5428262016702081418?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/alexscordellis/~3/Opp_eN8nusk/html-escaping-in-aspnet-mvc.html" title="HTML escaping in ASP.NET MVC" /><author><name>Alex Scordellis</name><uri>http://www.blogger.com/profile/04874376446759200232</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://3.bp.blogspot.com/_xSv6Z4_T9iE/TDyeFksaK2I/AAAAAAAAAJg/AjTKq_entbo/S220/P1030192_2_export.jpg" /></author><thr:total>5</thr:total><feedburner:origLink>http://alexscordellis.blogspot.com/2008/12/html-escaping-in-aspnet-mvc.html</feedburner:origLink></entry><entry gd:etag="W/&quot;Ck8ERHk4fip7ImA9WxRaGUs.&quot;"><id>tag:blogger.com,1999:blog-2788569112547349568.post-2216323683423356173</id><published>2008-11-20T20:41:00.011Z</published><updated>2008-12-22T15:46:45.736Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-12-22T15:46:45.736Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="XmlSerializer" /><category scheme="http://www.blogger.com/atom/ns#" term="nullable types" /><category scheme="http://www.blogger.com/atom/ns#" term="xml" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><title>Using XmlSerializer to deserialize into a Nullable&lt;int&gt;</title><content type="html">I recently had trouble deserializing an XML message which contained a nillable property which maps to a nullable value type in my C# class. I had the XML shown below (from a RESTful Rails service), and I wanted to map it to a class like this one:

&lt;pre class="c#" name="code"&gt;    
    public class Entity
    {
        [XmlElement("id")]
        public int Id { get; set; }

        [XmlElement("parent-id")]
        public int? ParentId { get; set; }

        [XmlElement("name")]
        public string Name { get; set; }
    }
&lt;/pre&gt;

&lt;pre class="xml" name="code"&gt;
&amp;lt;?xml version="1.0" encoding="UTF-8"?&gt;
&amp;lt;entities type="array"&gt;
  &amp;lt;entity&gt;
    &amp;lt;id type="integer"&gt;1&amp;lt;/id&gt;
    &amp;lt;name&gt;Foo&amp;lt;/name&gt;
    &amp;lt;parent-id type="integer" nil="true"/&gt;
  &amp;lt;/entity&gt;
  &amp;lt;entity&gt;
    &amp;lt;id type="integer"&gt;2&amp;lt;/id&gt;
    &amp;lt;name&gt;Bar&amp;lt;/name&gt;
    &amp;lt;parent-id type="integer"&gt;1&amp;lt;/parent-id&gt;
  &amp;lt;/entity&gt;
&amp;lt;/entities&gt;
&lt;/pre&gt;


As you can see, the XML represents a set of objects with a parent-child relationship. Root elements don't have a parent, so their ParentId field should be null. However when I used the XmlSerializer to deserialize this, it threw me a "System.FormatException: Input string was not in a correct format.". 
&lt;br/&gt;&lt;br/&gt;
Internet searches didn't show me anything, so I resorted to writing my own NullableInt type to use in place of int?. I'd be surprised if XmlSerializer doesn't have a built in way to handle nullable value types. What am I missing?

&lt;pre class="c#" name="code"&gt;
    public struct NullableInt : IXmlSerializable
    {
        private int value;
        private bool hasValue;
 
        private NullableInt(int value)
        {
            hasValue = true;
            this.value = value;
        }
 
        public bool HasValue
        {
            get { return hasValue; }
        }
 
        public int Value
        {
            get { return value; }
        }
 
        XmlSchema IXmlSerializable.GetSchema()
        {
            return null;
        }
 
        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            if (reader.GetAttribute("nil") == "true")
            {
                ReadNullValue();
                return;
            }
            ReadNonNullValue(reader);
        }
 
        void IXmlSerializable.WriteXml(XmlWriter writer)
        {
            throw new NotSupportedException();
        }
 
        private void ReadNullValue()
        {
            hasValue = false;
        }
 
        private void ReadNonNullValue(XmlReader reader)
        {
            reader.ReadStartElement();
            var s = reader.ReadString();
            value = Convert.ToInt32(s);
            reader.ReadEndElement();
            hasValue = true;
        }
 
        public static implicit operator NullableInt(int value)
        {
            return new NullableInt(value);
        }
    }
&lt;/pre&gt;

EDIT: See &lt;a href="http://stackoverflow.com/questions/306877/can-xmlserializer-deserialize-into-a-nullableint"&gt;this StackOverflow&lt;/a&gt; post for the solution.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2788569112547349568-2216323683423356173?l=alexscordellis.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/alexscordellis/~4/M5YxxV856x4" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://alexscordellis.blogspot.com/feeds/2216323683423356173/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://alexscordellis.blogspot.com/2008/11/using-xmlserializer-to-deserialize-into.html#comment-form" title="4 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/2216323683423356173?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/2216323683423356173?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/alexscordellis/~3/M5YxxV856x4/using-xmlserializer-to-deserialize-into.html" title="Using XmlSerializer to deserialize into a Nullable&amp;lt;int&amp;gt;" /><author><name>Alex Scordellis</name><uri>http://www.blogger.com/profile/04874376446759200232</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://3.bp.blogspot.com/_xSv6Z4_T9iE/TDyeFksaK2I/AAAAAAAAAJg/AjTKq_entbo/S220/P1030192_2_export.jpg" /></author><thr:total>4</thr:total><feedburner:origLink>http://alexscordellis.blogspot.com/2008/11/using-xmlserializer-to-deserialize-into.html</feedburner:origLink></entry><entry gd:etag="W/&quot;Ck8NRnc6fCp7ImA9WxRaGUs.&quot;"><id>tag:blogger.com,1999:blog-2788569112547349568.post-2907729249750455357</id><published>2008-10-30T20:42:00.010Z</published><updated>2008-12-22T15:48:17.914Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-12-22T15:48:17.914Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="acceptance testing" /><category scheme="http://www.blogger.com/atom/ns#" term="dtd" /><category scheme="http://www.blogger.com/atom/ns#" term="WebDriver" /><category scheme="http://www.blogger.com/atom/ns#" term="xml" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><category scheme="http://www.blogger.com/atom/ns#" term="dotnet" /><title>How to stop an XmlReader taking 5 seconds to load an HTML page</title><content type="html">If you've come for the answer to the title, &lt;a href="#meat"&gt;skip to the end&lt;/a&gt;!
&lt;br/&gt;&lt;br/&gt;
On my current project, we are writing a simple &lt;a href="http://code.google.com/p/webdriver/"&gt;WebDriver&lt;/a&gt; inspired framework for acceptance testing our web app (we'd give WebDriver a go, but we're on .NET). The framework gets the pages from the server using HttpRequests, inspects them using XPath etc, then builds forms to post back to the server. We chose to do this to make our tests run faster than they would in Selenium (of course, when there's JavaScript involved, we have to resort to Selenium).
&lt;br/&gt;&lt;br/&gt;
Unfortunately, we found that our tests were still taking a long time: 10-15 seconds to load a page, fill in a form, post it back and view the response. We had been hoping for much better performance - at this rate we might as well use Selenium! I was puzzled as to what was taking so long - surely it shouldn't take 5 seconds to load a smallish HTML page into an XmlDocument? I converted the code to use XPathDocument instead, as it's meant to be faster for read-only access, but saw little or no improvement (not really surprising on a small document).
&lt;br/&gt;&lt;br/&gt;
It wasn't until I was packing up to go home, and unplugged my laptop from the network while it was running these tests, that I found the problem: 

&lt;pre&gt;
               [nunit2] 9) A.Test.Name : System.Net.WebException : The remote name could
not be resolved: 'www.w3.org'
               [nunit2]    at System.Net.HttpWebRequest.GetResponse()
               [nunit2]    at System.Xml.XmlDownloadManager.GetNonFileStream(Uri uri, ICredentials credentials)
               [nunit2]    at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials)
               [nunit2]    at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
               [nunit2]    at System.Xml.XmlTextReaderImpl.OpenStream(Uri uri)
               [nunit2]    at System.Xml.XmlTextReaderImpl.DtdParserProxy_PushExternalSubset(String systemId, String publicId)
               [nunit2]    at System.Xml.XmlTextReaderImpl.DtdParserProxy.System.Xml.IDtdParserAdapter.PushExternalSubset(String systemId, String publ
icId)
               [nunit2]    at System.Xml.DtdParser.ParseExternalSubset()
               [nunit2]    at System.Xml.DtdParser.ParseInDocumentDtd(Boolean saveInternalSubset)
               [nunit2]    at System.Xml.DtdParser.Parse(Boolean saveInternalSubset)
               [nunit2]    at System.Xml.XmlTextReaderImpl.DtdParserProxy.Parse(Boolean saveInternalSubset)
               [nunit2]    at System.Xml.XmlTextReaderImpl.ParseDoctypeDecl()
               [nunit2]    at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
               [nunit2]    at System.Xml.XmlTextReaderImpl.Read()
               [nunit2]    at System.Xml.XPath.XPathDocument.LoadFromReader(XmlReader reader, XmlSpace space)
               [nunit2]    at System.Xml.XPath.XPathDocument..ctor(Stream stream)
&lt;/pre&gt;

I was surprised to see the &lt;tt&gt;XmlTextReader&lt;/tt&gt; going off to the web to fetch the DTD specified in my page's DOCTYPE tag. I suppose it is sometimes useful to validate pages in this way, but I wasn't really expecting it here.
&lt;br/&gt;&lt;br/&gt;
After a bit of googling, I found the answer on the increasingly useful &lt;a href="http://stackoverflow.com/questions/217841/net-autogenerated-web-service-client-how-do-i-avoid-requesting-schemas-from-w3o"&gt;stackoverflow.com&lt;/a&gt;. Just set the XmlResolver on your XmlReader to null, something like this:
&lt;br/&gt;&lt;br/&gt;
&lt;a name="meat"&gt;&lt;/a&gt;
&lt;pre name="code" class="c#"&gt;
var reader = new XmlTextReader(lastResponse.GetResponseStream()) {XmlResolver = null};
var navigator = new XPathDocument(reader).CreateNavigator();
&lt;/pre&gt;

One lesson here is that it's a good idea to periodically run your build disconnected to the network, just to reveal any unexpected dependencies you may have. I guess this won't always be possible - you might have genuine dependencies - but it's a useful tool in the 'shake it and see what comes out' category.
&lt;br/&gt;&lt;br/&gt;
&lt;b&gt;Edit:&lt;/b&gt;
It turned out that like &lt;a href="http://stackoverflow.com/questions/217841/net-autogenerated-web-service-client-how-do-i-avoid-requesting-schemas-from-w3o"&gt;Rasmus on stackoverflow.com&lt;/a&gt; I too needed to resolve entities. For example, my HTML contained a &amp;amp;nbsp; entity. Without the DTD and entity definitions, I couldn't load my XML document. So I also had to write a LocalXmlResolver to return those DTDs I needed from a embedded resource. All it needs to do is recognise URLs like http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd and http://www.w3.org/TR/xhtml1/DTD/xhtml-lat1.ent and return the appropriate content.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2788569112547349568-2907729249750455357?l=alexscordellis.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/alexscordellis/~4/tRJjzK3J8ZI" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://alexscordellis.blogspot.com/feeds/2907729249750455357/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://alexscordellis.blogspot.com/2008/10/how-to-stop-xmlreader-taking-5-seconds.html#comment-form" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/2907729249750455357?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/2907729249750455357?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/alexscordellis/~3/tRJjzK3J8ZI/how-to-stop-xmlreader-taking-5-seconds.html" title="How to stop an XmlReader taking 5 seconds to load an HTML page" /><author><name>Alex Scordellis</name><uri>http://www.blogger.com/profile/04874376446759200232</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://3.bp.blogspot.com/_xSv6Z4_T9iE/TDyeFksaK2I/AAAAAAAAAJg/AjTKq_entbo/S220/P1030192_2_export.jpg" /></author><thr:total>2</thr:total><feedburner:origLink>http://alexscordellis.blogspot.com/2008/10/how-to-stop-xmlreader-taking-5-seconds.html</feedburner:origLink></entry><entry gd:etag="W/&quot;Ck4BQnYyeSp7ImA9WxRaGUs.&quot;"><id>tag:blogger.com,1999:blog-2788569112547349568.post-1942138029385118070</id><published>2008-09-19T11:54:00.008+01:00</published><updated>2008-12-22T15:49:13.891Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-12-22T15:49:13.891Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="ruby" /><category scheme="http://www.blogger.com/atom/ns#" term="iTunes" /><title>Using Ruby to find non iTunes purchases to copy to a new machine</title><content type="html">I'm about to get a replacement laptop, so I need to copy all my stuff over, including music. With iTunes, it's easy to transfer songs that you've purchased from iTunes via your iPod (just don't forget to deauthorize your old machine before you dispose of it!), but not so easy to transfer all the music that you've downloaded from other sources, ripped from CDs, etc.
&lt;br/&gt;&lt;br/&gt;
I wrote the following Ruby script to find all such files in my iTunes library and copy them to another folder, from where I can burn them to CD, transfer them over a network etc. It does rely on all your downloaded and imported files being MP3 encoded, rather than AAC, since it uses the file extension to determine the relevant files. It also excludes everything in the Podcasts directory, since I can always download them again.
&lt;br/&gt;&lt;br/&gt;
Anyway, thought other people might find it useful.
&lt;pre class="ruby" name="code"&gt;
require 'find'
require 'ftools'
dirs = ["c:/path/to/my/itunes/library"]
excluded_extensions = %w(m4p m4a m4b m4v pdf).map { |ext| '.' + ext }
excluded_dirs = %w(Podcasts)
target = "C:/music/to/copy/to/new/machine"
files = []
for dir in dirs
  Find.find(dir) do |path|
    if FileTest.directory?(path)
      if excluded_dirs.include?(File.basename(path))
        Find.prune
      else
        next
      end
    else
      if excluded_extensions.include?(File.extname(path))
        next
      else
        puts path
        files &lt;&lt; path
      end
    end
  end
end

files.each do |file|
  File.copy(file, target + File.basename(file), true)
end
&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2788569112547349568-1942138029385118070?l=alexscordellis.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/alexscordellis/~4/k-XIjMnmLSA" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://alexscordellis.blogspot.com/feeds/1942138029385118070/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://alexscordellis.blogspot.com/2008/09/using-ruby-to-find-non-itunes-purchases.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/1942138029385118070?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/1942138029385118070?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/alexscordellis/~3/k-XIjMnmLSA/using-ruby-to-find-non-itunes-purchases.html" title="Using Ruby to find non iTunes purchases to copy to a new machine" /><author><name>Alex Scordellis</name><uri>http://www.blogger.com/profile/04874376446759200232</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://3.bp.blogspot.com/_xSv6Z4_T9iE/TDyeFksaK2I/AAAAAAAAAJg/AjTKq_entbo/S220/P1030192_2_export.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://alexscordellis.blogspot.com/2008/09/using-ruby-to-find-non-itunes-purchases.html</feedburner:origLink></entry><entry gd:etag="W/&quot;Ck4NQ3o-cSp7ImA9WxRaGUs.&quot;"><id>tag:blogger.com,1999:blog-2788569112547349568.post-8675438128365650273</id><published>2008-09-11T11:55:00.005+01:00</published><updated>2008-12-22T15:49:52.459Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-12-22T15:49:52.459Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="mercurial" /><category scheme="http://www.blogger.com/atom/ns#" term="version control" /><category scheme="http://www.blogger.com/atom/ns#" term="git" /><category scheme="http://www.blogger.com/atom/ns#" term="github" /><category scheme="http://www.blogger.com/atom/ns#" term="windows" /><title>Converting Mercurial to Git on Windows</title><content type="html">&lt;h4&gt;Summary&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;If you want to convert a Mercurial repository to a Git repository, without losing history, on a Windows machine, use Stelian Pop's &lt;a href="http://hopper.squarespace.com/blog/2008/7/5/converting-mercurial-to-git.html"&gt;script&lt;/a&gt;, but you'll need to run it under Cygwin.&lt;/li&gt;
&lt;li&gt;Prefer using &lt;a href="http://code.google.com/p/msysgit/"&gt;msysGit&lt;/a&gt; for interactions with Github, since all the instructions for &lt;a href="http://www.github.com/guides/using-git-and-github-for-the-windows-for-newbies"&gt;configuring it&lt;/a&gt; and &lt;a href="http://www.github.com/guides/dealing-with-newlines-in-git"&gt;dealing with newlines&lt;/a&gt; are clearly explained for you.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;The Story&lt;/h4&gt;
I've got a Ruby script for generating graphs of build duration and other metrics from CruiseControl, and it was in a Mercurial repository on my Windows machine. I'd chosen Mercurial for a couple of reasons:
&lt;ul&gt;
&lt;li&gt;I wanted to try out one of these newly popular distributed version control systems to see what the fuss is all about.&lt;/li&gt;
&lt;li&gt;I was writing the code on my laptop, then copying it to a machine on my client's network so I could run it against our CruiseControl build. I wanted to be able to make modifications on the other machine, perhaps in parallel to modifications on my laptop, and port them back. With Mercurial, the process was simple (zip up my repository from my laptop, email it to myself at my gmail account, download onto client machine, unzip, modify code, commit, rezip, re-email, unzip on laptop in a different location, 'hg pull' from new location to original location).&lt;/li&gt;
&lt;/ul&gt;
Mercurial seemed relatively simple to use, coming from a Subversion background. You can use it locally just as if it was Subversion, then worry about pulling and pushing once you need the distributed facilities or need to share your code. It even has the TortoiseHg Windows shell integration.
&lt;br/&gt;&lt;br/&gt;
However all the hype these days seems to be about Git. I also wanted to get my code up on the web so others could have a go, and &lt;a href="http://www.github.com/"&gt;Github&lt;/a&gt; seemed to be the most natural place to put it. I wanted to keep the history of the project, so I started looking for a way to convert a Mercurial repository to Git. I found Ben Hood's &lt;a href="http://hopper.squarespace.com/blog/2008/7/5/converting-mercurial-to-git.html"&gt;blog post&lt;/a&gt;. However my msysGit bash shell installation (where I had been doing most of my Git work), did not have Python available. So I installed the git package into my local Cygwin installation, and the script worked there. I then went back to msysGit's bash shell for the upload to my &lt;a href="http://www.github.com/alexscordellis/build-monitor"&gt;Github repository&lt;/a&gt;, since I'd configured it with my SSH key etc as suggested by the &lt;a href="http://www.github.com/guides/using-git-and-github-for-the-windows-for-newbies"&gt;Github guide for Windows&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2788569112547349568-8675438128365650273?l=alexscordellis.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/alexscordellis/~4/diA2Q_dO19g" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://alexscordellis.blogspot.com/feeds/8675438128365650273/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://alexscordellis.blogspot.com/2008/09/converting-mercurial-to-git-on-windows.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/8675438128365650273?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/8675438128365650273?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/alexscordellis/~3/diA2Q_dO19g/converting-mercurial-to-git-on-windows.html" title="Converting Mercurial to Git on Windows" /><author><name>Alex Scordellis</name><uri>http://www.blogger.com/profile/04874376446759200232</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://3.bp.blogspot.com/_xSv6Z4_T9iE/TDyeFksaK2I/AAAAAAAAAJg/AjTKq_entbo/S220/P1030192_2_export.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://alexscordellis.blogspot.com/2008/09/converting-mercurial-to-git-on-windows.html</feedburner:origLink></entry><entry gd:etag="W/&quot;C0YHRn4_cSp7ImA9WxRaGUs.&quot;"><id>tag:blogger.com,1999:blog-2788569112547349568.post-355982546645557631</id><published>2008-09-02T16:56:00.012+01:00</published><updated>2008-12-22T15:52:17.049Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-12-22T15:52:17.049Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="reflection" /><category scheme="http://www.blogger.com/atom/ns#" term="NSynthesis" /><category scheme="http://www.blogger.com/atom/ns#" term="generics" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><title>Generics and reflection in .NET</title><content type="html">This week I've been working on the implementation of generics in NSynthesis. It's mostly involved some pretty hairy reflection code, often with a lot of edge cases.
&lt;br/&gt;&lt;br/&gt;
To verify that you have tests of all production implementations of mocked methods, NSynthesis goes through two main procedures
&lt;ol&gt;&lt;li&gt;For each mock call observed, identify all possible implementing methods.&lt;/li&gt;
&lt;li&gt;For each real call observed in a unit test, tick off an implementing method we identified in step one.&lt;/li&gt;&lt;/ol&gt;Both of these steps aren't too hard when there aren't generics involved. For step one, just walk the inheritance tree looking for methods with the appropriate signature. For step two, you can just ask the MethodInfo objects to compare each other.
&lt;br/&gt;&lt;br/&gt;
Generics introduce a whole new set of problems. I posted last week about the rules that I think we should follow, but implementing them is pretty hard. For example, if we ask the CLR:  typeof (IService&amp;lt;Customer&amp;gt;).IsAssignableFrom(typeof (Service&amp;lt;&amp;gt;)));, the answer is rightly false, but that makes it harder to detect that a method you've found on Service&amp;lt;T&amp;gt; is a potential implementation for your mock call to a method on IService&amp;lt;Customer&amp;gt;.
&lt;br/&gt;&lt;br/&gt;
I made some progress on step one, to the extent that all the implementations of IService&amp;lt;Customer&amp;gt; that I mentioned in &lt;a href="http://alexscordellis.blogspot.com/2008/08/synthesised-testing-and-net-generics.html"&gt;my earlier post&lt;/a&gt; are picked up. It took me a while and is nowhere near finished (e.g. it won't find implementations of mock calls that are not to interfaces) but I did learn a few useful things along the way:

&lt;ul&gt;
&lt;li&gt;Type.IsGenericTypeDefinition&lt;/li&gt;
&lt;li&gt;Type.IsGenericType&lt;/li&gt;
&lt;li&gt;MethodInfo.IsGenericMethodDefinition&lt;/li&gt;
&lt;li&gt;MethodInfo.IsGenericMethod&lt;/li&gt;
&lt;/ul&gt;

IsGenericType will return true for any Type object where the type has type parameters, e.g. typeof(Repository&amp;lt;Customer&amp;gt;) or typeof(Repository&amp;lt;&amp;gt;).
&lt;br/&gt;&lt;br/&gt;
IsGenericTypeDefinition will only return true for typeof(Repository&amp;lt;&amp;gt;), not typeof(Repository&amp;lt;Customer&amp;gt;). You can go between typeof(Repository&amp;lt;&amp;gt;) and typeof(Repository&amp;lt;Customer&amp;gt;) with the methods GetGenericTypeDefinition() and MakeGenericType(params Type[]). Note that to make a generic type from a generic type definition, you need to provide the type parameters.
&lt;br/&gt;&lt;br/&gt;
The same thing applies to methods, with the one gotcha that IService&amp;lt;T&amp;gt;.Method() is not a generic method, and IService.Method&amp;lt;T&amp;gt;() is. In other words, you need the method itself to have the generic type parameters, rather than its declaring type.
&lt;br/&gt;&lt;br/&gt;
Having got that far with step one, I decided to move to step 2: matching test-runtime invocations of production code to the methods that we decided needed testing during step one. The good news here is that inheritance doesn't get involved. We now just want to check that every method was called. It sounds easy, and prior to generics, it was. In fact, &lt;a href="http://no-new-ideas.blogspot.com/"&gt;Stuart&lt;/a&gt;'s implementation which worked for non-generics just compared the two MethodInfo objects using their Equals method. This won't work for generics - remember that we want Service&amp;lt;Widget&amp;gt;.Load() to satisfy our need for a test of Service&amp;lt;Customer&amp;gt;.Load(), but the MethodInfo's typeof(Service&amp;lt;Widget&amp;gt;).GetMethod("Load") and typeof(Service&amp;lt;Customer&amp;gt;).GetMethod("Load") are not counted as equal.
&lt;br/&gt;&lt;br/&gt;
It turns out that what we get from PostSharp capturing our test call is equivalent to typeof(Service&amp;lt;Customer&amp;gt;).GetMethod("Load"), but what we got from step one of NSynthesis is equivalent to typeof(Service&amp;lt;&amp;gt;).GetMethod("Load"). I started digging deep into the reflection objects, with code like
&lt;pre class="c#" name="code"&gt;
        private bool MethodCalledIsDeclaredOnClosureOfGenericTypeDefinition(Type typeDeclaringMethodToSatisfy)
        {
            return
                typeDeclaringMethodToSatisfy.IsGenericTypeDefinition &amp;&amp;
                TypeDeclaringMethodCalled.IsGenericType &amp;&amp;
                !TypeDeclaringMethodCalled.IsGenericTypeDefinition &amp;&amp; TypeDeclaringMethodCalled.GetGenericTypeDefinition().Equals(typeDeclaringMethodToSatisfy);
        }
&lt;/pre&gt;

and

&lt;pre class="c#" name="code"&gt;
        private bool SignatureMatchesGeneric(MethodInfo methodToSatisfy)
        {
            if (methodToSatisfy.Name != methodCalled.Name)
                return false;
            if (methodToSatisfy.GetParameters().Count() != methodCalled.GetParameters().Count())
                return false;
            for (int i = 0; i != methodToSatisfy.GetParameters().Count(); i++)
            {
                if (methodToSatisfy.GetParameters()[i].ParameterType.IsGenericParameter)
                {
                    var genericParameterPosition = methodToSatisfy.GetParameters()[i].ParameterType.GenericParameterPosition;
                    if (!(methodCalled.GetParameters()[i].ParameterType == methodCalled.DeclaringType.GetGenericArguments()[genericParameterPosition]))
                        return false;
                }
                else
                {
                    if (!methodToSatisfy.GetParameters()[i].ParameterType.Equals(methodCalled.GetParameters()[i].ParameterType))
                        return false;
                }
            }
            return true;
        }
&lt;/pre&gt;

which does all sorts of comparing of positions of generic type parameters and so on. It only covers a few cases too. For example it wouldn't work if a parameter to a method had type IList&amp;lt;T&amp;gt; - I was dreading having to dig arbitrarily deep into nesting of generic parameters - nor in the case when both the type and the method had generic type parameters.
&lt;br/&gt;&lt;br/&gt;
Fortunately I then discovered the MetadataToken property of the MemberInfo class. It &lt;i&gt;appears&lt;/i&gt; (so far!) to give a unique number for each method body, which is exactly what we need for NSynthesis. So all that code above (and there was more of it!) got replaced by 
&lt;pre class="c#" name="code"&gt;
        public bool Satisfies(MethodInfo methodToSatisfy)
        {
            return methodCalled.MetadataToken.Equals(methodToSatisfy.MetadataToken);
        }
&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2788569112547349568-355982546645557631?l=alexscordellis.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/alexscordellis/~4/3FEJflV1fp8" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://alexscordellis.blogspot.com/feeds/355982546645557631/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://alexscordellis.blogspot.com/2008/09/generics-and-reflection-in-net.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/355982546645557631?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/355982546645557631?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/alexscordellis/~3/3FEJflV1fp8/generics-and-reflection-in-net.html" title="Generics and reflection in .NET" /><author><name>Alex Scordellis</name><uri>http://www.blogger.com/profile/04874376446759200232</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://3.bp.blogspot.com/_xSv6Z4_T9iE/TDyeFksaK2I/AAAAAAAAAJg/AjTKq_entbo/S220/P1030192_2_export.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://alexscordellis.blogspot.com/2008/09/generics-and-reflection-in-net.html</feedburner:origLink></entry><entry gd:etag="W/&quot;C0YDSHs6fip7ImA9WxRaGUs.&quot;"><id>tag:blogger.com,1999:blog-2788569112547349568.post-440572734361516978</id><published>2008-08-29T12:41:00.013+01:00</published><updated>2008-12-22T15:52:59.516Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-12-22T15:52:59.516Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="mocks" /><category scheme="http://www.blogger.com/atom/ns#" term="NSynthesis" /><category scheme="http://www.blogger.com/atom/ns#" term="generics" /><category scheme="http://www.blogger.com/atom/ns#" term="testing" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><title>Synthesized testing and .NET generics</title><content type="html">I'm working with my colleage &lt;a href="http://no-new-ideas.blogspot.com/"&gt;Stuart Caborn&lt;/a&gt; on NSynthesis, a .NET implementation of the theory of Synthesized Testing. If you've not heard about Synthesis, or Synthesized Testing, I'll give a quick introduction. In general, the idea is to enforce that whenever you've mocked out a method during a unit test of a class calling that method, you've also got a unit test for all concrete implementations of that method. This increases your confidence that your mock tests and your concrete tests join up, without making you write any of those pesky slow functional tests.
&lt;br/&gt;&lt;br/&gt;
There's much more to be found on Stuart's blog, and that of &lt;a href="http://www.nutrun.com/"&gt;George Malamidis&lt;/a&gt; who wrote the original Ruby implementation.
&lt;ul&gt;&lt;li&gt;&lt;a href="http://nutrun.com/weblog/synthesized-testing-a-primer/"&gt;Synthesized Testing: A Primer&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="http://no-new-ideas.blogspot.com/2008/03/synthesis-and-test-confidence.html"&gt;Synthesis and test confidence&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="http://synthesis.rubyforge.org/"&gt;Ruby implementation&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="http://nutrun.com/weblog/synthesized-testing-slides/"&gt;Slides from Stuart and George's talk on the topic&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;
The problem we're having with NSynthesis is: what do we do about generics? This blog post is me thinking out loud about this problem. We're pretty clear that if you've mocked IService.Method(), then you need a unit test for ConcreteService.Method() and OtherConcreteService.Method(), where ConcreteService and OtherConcreteService are all the known classes implementing IService. But what if I've mocked IService&amp;lt;Customer&amp;gt;.Method() or IService.Method&amp;lt;Customer&amp;gt;()? On which methods should we now be demanding unit tests?
&lt;br/&gt;&lt;br/&gt;
I think if I've mocked methods on IService&amp;lt;Customer&amp;gt; and there exists a class CustomerService : IService&amp;lt;Customer&amp;gt;, then NSynthesis should demand unit tests of the corresponding methods on CustomerService. But what if there isn't a CustomerService, but rather just Service&amp;lt;T&amp;gt; : IService&amp;lt;T&amp;gt;? My first reaction is to demand unit tests for methods on Service&amp;lt;Customer&amp;gt;.
&lt;br/&gt;&lt;br/&gt;
But what happens then when I mock IService&amp;lt;Product&amp;gt;? Do I now need unit tests for methods on Service&amp;lt;Product&amp;gt;? If I follow this path then I'll have many duplicate tests of my Service&amp;lt;T&amp;gt; class. That's got to be wrong. So unit tests of Service&amp;lt;Customer&amp;gt; should satisfy mock calls to IService&amp;lt;Product&amp;gt;.
&lt;br/&gt;&lt;br/&gt;
But now I realise that for Widgets, I need a special implementation of IService&amp;lt;Widget&amp;gt;. So I introduce WidgetService : Service&amp;lt;Widget&amp;gt;. WidgetService overrides some of the methods in Service&amp;lt;Widget&amp;gt;. I should probably demand unit tests of these methods too (assuming I have mock calls to these methods on IService&amp;lt;Widget&amp;gt;).
&lt;br/&gt;&lt;br/&gt;
If you're interested in Synthesized Testing you can join the &lt;a href="http://groups.google.com/group/synthesized-testing"&gt;mailing list&lt;/a&gt; or check out the &lt;a href="http://code.google.com/p/jsynthesis/"&gt;Java version&lt;/a&gt;. I wonder how they are handling generics?&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2788569112547349568-440572734361516978?l=alexscordellis.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/alexscordellis/~4/SitrFGHEIQ4" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://alexscordellis.blogspot.com/feeds/440572734361516978/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://alexscordellis.blogspot.com/2008/08/synthesised-testing-and-net-generics.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/440572734361516978?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/2788569112547349568/posts/default/440572734361516978?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/alexscordellis/~3/SitrFGHEIQ4/synthesised-testing-and-net-generics.html" title="Synthesized testing and .NET generics" /><author><name>Alex Scordellis</name><uri>http://www.blogger.com/profile/04874376446759200232</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://3.bp.blogspot.com/_xSv6Z4_T9iE/TDyeFksaK2I/AAAAAAAAAJg/AjTKq_entbo/S220/P1030192_2_export.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://alexscordellis.blogspot.com/2008/08/synthesised-testing-and-net-generics.html</feedburner:origLink></entry></feed>

