<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Richard Dingwall</title>
	
	<link>http://richarddingwall.name</link>
	<description>The adventures of a young kiwi software developer in London</description>
	<lastBuildDate>Fri, 30 Dec 2011 13:25:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/RichardDingwall" /><feedburner:info uri="richarddingwall" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Object-oriented basics: single object or collection scope?</title>
		<link>http://feedproxy.google.com/~r/RichardDingwall/~3/qM9ybYzumV8/</link>
		<comments>http://richarddingwall.name/2011/12/30/object-oriented-basics-single-object-or-collection-scope/#comments</comments>
		<pubDate>Fri, 30 Dec 2011 13:25:33 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Fundamentals]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[SOLID]]></category>
		<category><![CDATA[SRP]]></category>

		<guid isPermaLink="false">http://richarddingwall.name/?p=4580</guid>
		<description><![CDATA[Here is a contrived example of a common SOLID violation you might see. Can you spot it? Except in trivially simple cases, there should always be a class boundary when shifting context from coordinating a collection versus performing actions on a single object. The class above is violating this rule &#8212; it knows how to [...]]]></description>
			<content:encoded><![CDATA[<p>Here is a contrived example of a common <a href="http://lostechies.com/chadmyers/2008/03/08/pablo-s-topic-of-the-month-march-solid-principles/">SOLID</a> violation you might see. Can you spot it?</p>
<pre class="brush: csharp; title: ; notranslate">
class Mp3Encoder : IMp3Encoder
{
    public void Encode(IEnumerable&lt;string&gt; wavFiles)
    {
        foreach (var wavFile in wavFiles)
        {
            var outputFile = /* create output file */;

            while (/* blocks remaining... */)
            {
                var buffer = /* read block */;
                var encoded = /* encode wav block as MP3 */;
                /* write block to output file */;
            }

            /* write ID3 trailing header */;
        }
    }
}</pre>
<p>Except in trivially simple cases, there should always be a class boundary when shifting context from <strong>coordinating a collection</strong> versus <strong>performing actions on a single object</strong>.</p>
<p>The class above is violating this rule &#8212; it knows how to perform collection-level responsibilities as well as single-object responsibilities. It needs to be broken into two classes; one for encoding a single file and one for coordinating the group.</p>
<p>This rule is a form of the <a href="http://www.oodesign.com/single-responsibility-principle.html">Single Responsibility Principle</a>. For example:</p>
<h5>Collection-scoped class responsibilities</h5>
<ul>
<li>Coordinating &#8216;before all&#8217; and &#8216;after all&#8217; actions</li>
<li>Looping through items</li>
<li>Maintaining shared state (counting, accumulating etc)</li>
</ul>
<h5>Single object-scoped class responsibilities</h5>
<ul>
<li>Coordinating &#8216;before each&#8217; and &#8216;after each&#8217; actions</li>
<li>Performing actions on item</li>
</ul>
<p>If you ignore this collection-vs-single-object contextual boundary, your classes will become messes of nested procedural code &#8212; especially when different behaviour is required for each item in the collection. Your classes will be that much harder to unit test, and you won&#8217;t easily be able to re-use them in single-object scenarios.</p>
<img src="http://feeds.feedburner.com/~r/RichardDingwall/~4/qM9ybYzumV8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://richarddingwall.name/2011/12/30/object-oriented-basics-single-object-or-collection-scope/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://richarddingwall.name/2011/12/30/object-oriented-basics-single-object-or-collection-scope/</feedburner:origLink></item>
		<item>
		<title>Subscribing to NuGet package updates via RSS</title>
		<link>http://feedproxy.google.com/~r/RichardDingwall/~3/Dugv6BRfQ_Q/</link>
		<comments>http://richarddingwall.name/2011/12/18/subscribing-to-nuget-package-updates-via-rss/#comments</comments>
		<pubDate>Sun, 18 Dec 2011 13:58:22 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://richarddingwall.name/?p=4557</guid>
		<description><![CDATA[Just a quick tip I found today &#8211; If you&#8217;re a NuGet package author and want to be notified when updates are published for upstream packages you depend, you can do so by subscribing to an OData query in an RSS reader. For example, in order to keep protobuf-net-data in sync with the latest protobuf-net, [...]]]></description>
			<content:encoded><![CDATA[<p>Just a quick tip I found today &#8211; If you&#8217;re a NuGet package author and want to be notified when updates are published for upstream packages you depend, you can do so by subscribing to an OData query in an RSS reader.</p>
<p>For example, in order to keep <a href="http://nuget.org/packages/protobuf-net-data">protobuf-net-data</a> in sync with the latest <a href="http://nuget.org/packages/protobuf-net">protobuf-net</a>, I need to publish a new package rebuilt against the latest protobuf-net data every time they release a new version. For this I subscribed to the following URL in Google Reader:</p>
<p><a href="http://packages.nuget.org/v1/FeedService.svc/Packages()?$filter=Id eq 'protobuf-net'">http://packages.nuget.org/v1/FeedService.svc/Packages()?$filter=Id eq &#8216;protobuf-net&#8217;</a></p>
<p><a href="http://www.mattwrock.com/post/2011/11/28/Track-Nuget-Downloads-using-OData-RSS-and-Iftttcom.aspx">Matt Wrock has a few more advanced examples of this</a> using ifttt.com to orchestrate sending emails and tracking package downloads etc.</p>
<img src="http://feeds.feedburner.com/~r/RichardDingwall/~4/Dugv6BRfQ_Q" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://richarddingwall.name/2011/12/18/subscribing-to-nuget-package-updates-via-rss/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://richarddingwall.name/2011/12/18/subscribing-to-nuget-package-updates-via-rss/</feedburner:origLink></item>
		<item>
		<title>Protocol Buffers DataReader Extensions for .NET</title>
		<link>http://feedproxy.google.com/~r/RichardDingwall/~3/AqUQbwHNZbo/</link>
		<comments>http://richarddingwall.name/2011/11/01/protocol-buffers-datareader-extensions-for-net/#comments</comments>
		<pubDate>Tue, 01 Nov 2011 23:52:20 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Protocol Buffers]]></category>

		<guid isPermaLink="false">http://richarddingwall.name/?p=4507</guid>
		<description><![CDATA[.NET, as a mostly-statically typed language, has a lot of really good options for serializing statically-typed objects. Protocol Buffers, MessagePack, JSON, BSON, XML, SOAP, and the BCL&#8217;s own proprietary binary serialization are all great for CLR objects, where the fields can be determined at runtime. However, for data that is tabular in nature, there aren&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p>.NET, as a mostly-statically typed language, has a lot of really good options for serializing statically-typed objects. Protocol Buffers, MessagePack, JSON, BSON, XML, SOAP, and the BCL&#8217;s own proprietary binary serialization are all great for CLR objects, where the fields can be determined at runtime.</p>
<p>However, for data that is tabular in nature, there aren&#8217;t so many options. In my past two jobs I&#8217;ve had a need to serialize data:</p>
<ul>
<li>That is tabular &#8211; not necessarily CLR DTOs.</li>
<li>Where the schema is unknown before it is deserialized &#8211; each data set can have totally different columns.</li>
<li>In a way that is streamable, so entire entire data sets do not have to be buffered in memory at once.</li>
<li>That can be as large as hundreds of thousands of rows/columns.</li>
<li>In a reasonably performant manner.</li>
<li>In a way that could potentially be read by different platforms.</li>
<li>Into as small a number of bytes as possible.</li>
</ul>
<p><a href="https://github.com/rdingwall/protobuf-net-data"><strong>Protocol Buffers DataReader Extensions for .NET</strong></a> was born out of these needs. It&#8217;s powered by Marc Gravell&#8217;s excellent Google Protocol Buffers library, <a href="http://code.google.com/p/protobuf-net/">protobuf-net</a>, and it packs data faster and smaller than the equivalent DataTable.Save/Write XML:</p>
<p><img src="http://richarddingwall.name/wp-content/uploads/2011/11/protobuf-net-data-benchmarks.png" alt="" title="protobuf-net-data-benchmarks" width="696" height="432" class="aligncenter size-full wp-image-4551" /></p>
<p>Usage is very easy. Serializing a data reader to a stream:</p>
<pre class="brush: csharp; title: ; notranslate">DataTable dt = ...;

using (Stream stream = File.OpenWrite(&quot;C:\foo.dat&quot;))
using (IDataReader reader = dt.CreateDataReader())
{
    DataSerializer.Serialize(stream, reader);
}</pre>
<p>Loading a data table from a stream:</p>
<pre class="brush: csharp; title: ; notranslate">DataTable dt = new DataTable();

using (Stream stream = File.OpenRead(&quot;C:\foo.dat&quot;))
using (IDataReader reader = DataSerializer.Deserialize(stream))
{
    dt.Load(reader);
}</pre>
<p>It works with IDataReaders, DataTables and DataSets (even nested DataTables). You can download the <a href="http://nuget.org/List/Packages/protobuf-net-data">protobuf-net-data</a> from NuGet, or grab the source from <a href="https://github.com/rdingwall/protobuf-net-data">the GitHub project page</a>.</p>
<img src="http://feeds.feedburner.com/~r/RichardDingwall/~4/AqUQbwHNZbo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://richarddingwall.name/2011/11/01/protocol-buffers-datareader-extensions-for-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://richarddingwall.name/2011/11/01/protocol-buffers-datareader-extensions-for-net/</feedburner:origLink></item>
		<item>
		<title>Failing the tube test</title>
		<link>http://feedproxy.google.com/~r/RichardDingwall/~3/hMuzK8IRRik/</link>
		<comments>http://richarddingwall.name/2011/10/01/failing-the-tube-test/#comments</comments>
		<pubDate>Sat, 01 Oct 2011 19:20:38 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[iOS]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[UX]]></category>

		<guid isPermaLink="false">http://richarddingwall.name/?p=4513</guid>
		<description><![CDATA[As a Londoner working in the city, I (along with hundreds of thousands of others) catch the tube to work every day. Although you&#8217;re typically crammed in a carriage with hundreds of other commuters, the journey is a solitary one, and many passengers turn to their iPhones, iPads and Kindles to pass the time. For [...]]]></description>
			<content:encoded><![CDATA[<p>As a Londoner working in the city, I (along with hundreds of thousands of others) catch the tube to work every day. Although you&#8217;re typically crammed in a carriage with hundreds of other commuters, the journey is a solitary one, and many passengers turn to their iPhones, iPads and Kindles to pass the time.</p>
<p><img src="http://travel.rentholidayapartmentlondon.co.uk/wp-content/uploads/2011/07/london_underground.jpg" class="aligncenter" /></p>
<p>For me, it&#8217;s a pretty long journey, up to an hour each way to get from Parsons Green to Canary Wharf &#8212; a large portion of which is spent deep underground, with no mobile or 3G coverage on my iPhone 4. During this time you can really tell which apps&#8217; data strategies have been properly thought out and designed, and which ones have been hacked together in a hurry.</p>
<p>I&#8217;m not going to mention any offending games or apps by name, but these are the sort of things developers should be shot for:</p>
<h4>Apps that don&#8217;t cache downloaded data for later viewing</h4>
<p>Except in special cases (e.g. streaming audio/video, realtime or sensitive content),  all downloaded data must be cached locally, and able to be viewed again without an internet connection. Apps that don&#8217;t store downloaded content are just crippled web browsers.</p>
<h4>Offline App Store reviews</h4>
<p>It is unacceptable to nag me to rate your app in the App Store when there is no internet connection. Honestly &#8212; don&#8217;t ask users to do the impossible.</p>
<h4>Repeated connection attempts and repeated error diaglogs</h4>
<p>It is unacceptable to repeatedly show error dialogs when there is no internet connection. By all means, try to continuously download updates, but do it silently and in the background. I do not need to be told every 30 seconds that it (still) couldn&#8217;t connect.</p>
<h4>Locking the UI when checking for updates on startup</h4>
<p>When launched, It is unacceptable to block the user in the UI from reading previously-cached data while downloading updated content. By all means, check for updates on start up, but while that is happening, the user must be able to read the previous cached copy, unless they explicitly asked for a refresh from-scratch.</p>
<h4>Throwing away cached data then failing to update</h4>
<p>It is unacceptable to leave the user with a blank screen because you threw away previously-cached data THEN failed to update. Local data caches should not be cleared until new data has been 100% retrieved successfully and loaded.</p>
<h4>Lost form data, please retype</h4>
<p>t is unacceptable to &#8216;lose&#8217; form values and force the user to retype a message when a submit error occurs. Form values must be saved somewhere &#8212; either automatically requeued for resubmission, or as a draft that can be edited or cancelled by the user.</p>
<h4>Ad priorities</h4>
<p>It is unacceptable for an ad-supported app to crash, refuse to start or behave weirdly because it couldn&#8217;t connect to the ad server. Are you worried about people using your app, or seeing ads?</p>
<h4>Occasionally connected apps</h4>
<p>It is unacceptable for any app to refuse to start without an internet connection. Users should always be able to change settings, view and edit previously-cached data and enqueue new requests where possible (to be submitted when a connection is available).</p>
<h4>Final thoughts</h4>
<p>In general, occasionally-connected computing is a good model for iPhone/Android apps that push/pull data from the Internet. It just needs to be implemented correctly. Like web designers assuming no javascript and using progressive-enhancement to add improved behaviour on top of basic functionality, mobile developers should assume no internet connection is available most of the time &#8212; jump at the opportunity to sync when possible, but don&#8217;t interrupt the user or assume it won&#8217;t fail.</p>
<p>So please, if If you&#8217;re a mobile developer, think about us poor Londoners before you deploy your next version!</p>
<img src="http://feeds.feedburner.com/~r/RichardDingwall/~4/hMuzK8IRRik" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://richarddingwall.name/2011/10/01/failing-the-tube-test/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://richarddingwall.name/2011/10/01/failing-the-tube-test/</feedburner:origLink></item>
		<item>
		<title>SqlDropDatabase, SqlCreateDatabase MSBuild tasks</title>
		<link>http://feedproxy.google.com/~r/RichardDingwall/~3/BRktn2Ud5e4/</link>
		<comments>http://richarddingwall.name/2011/08/22/sqldropdatabase-sqlcreatedatabase-msbuild-tasks/#comments</comments>
		<pubDate>Mon, 22 Aug 2011 21:59:10 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Deployment]]></category>
		<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false">http://richarddingwall.name/?p=4493</guid>
		<description><![CDATA[When working with SQL, I often find I need to quickly spin up/tear down local developer database instances &#8211; for example, setting up a clean environment for integration tests on the build server, or blowing away test data. To help make this easier, here are a couple of MSBuild tasks I wrote that allow you [...]]]></description>
			<content:encoded><![CDATA[<p>When working with SQL, I often find I need to quickly spin up/tear down local developer database instances &#8211; for example, setting up a clean environment for integration tests on the build server, or  blowing away test data.</p>
<p>To help make this easier, here are a couple of MSBuild tasks I wrote that allow you to drop an existing database:</p>
<pre class="brush: xml; title: ; notranslate">&lt;SqlDropDatabase ConnectionString=&quot;Server=.\SQLEXPRESS;Database=AdventureWorks;Integrated Security=SSPI;&quot;
                 Database=&quot;AdventureWorks&quot; /&gt;</pre>
<p>&#8230; and to create a new (empty) one.</p>
<pre class="brush: xml; title: ; notranslate">&lt;SqlCreateDatabase ConnectionString=&quot;Server=.\SQLEXPRESS;Database=AdventureWorks;Integrated Security=SSPI;&quot;
                   Database=&quot;AdventureWorks&quot; /&gt;</pre>
<p>It&#8217;s also sometimes helpful to be able to parse individual individual keys out of a connection string (e.g. the the database name). This can be very tedious with RegexMatch/RegexReplace, so I wrote a separate MSBuild task to do it:</p>
<pre class="brush: xml; title: ; notranslate">&lt;SqlParseConnectionString ConnectionString=&quot;Server=.\SQLEXPRESS;Database=AdventureWorks;Integrated Security=SSPI;&quot;&gt;
    &lt;Output PropertyName=&quot;myDb&quot; TaskParameter=&quot;InitialCatalog&quot; /&gt;
    &lt;Output PropertyName=&quot;myServer&quot; TaskParameter=&quot;DataSource&quot; /&gt;
    &lt;Output PropertyName=&quot;myTimeout&quot; TaskParameter=&quot;ConnectTimeout&quot; /&gt;
&lt;/SqlParseConnectionString&gt;
&lt;Message Text=&quot;Parsed the $(myDb) database on server $(myServer) with timeout = $(myTimeout).&quot; /&gt;</pre>
<p>You can grab the code here: <a href="http://github.com/rdingwall/sqlmsbuildtasks">http://github.com/rdingwall/sqlmsbuildtasks</a></p>
<img src="http://feeds.feedburner.com/~r/RichardDingwall/~4/BRktn2Ud5e4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://richarddingwall.name/2011/08/22/sqldropdatabase-sqlcreatedatabase-msbuild-tasks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://richarddingwall.name/2011/08/22/sqldropdatabase-sqlcreatedatabase-msbuild-tasks/</feedburner:origLink></item>
		<item>
		<title>Fragmented integration tests – aka the questionable value zone</title>
		<link>http://feedproxy.google.com/~r/RichardDingwall/~3/1DOKUBw5BBE/</link>
		<comments>http://richarddingwall.name/2011/05/14/fragmented-integration-tests-aka-the-questionable-value-zone/#comments</comments>
		<pubDate>Sat, 14 May 2011 12:34:20 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">http://richarddingwall.name/?p=4366</guid>
		<description><![CDATA[In TDD, different styles of tests can be applied to cover different levels in your code base. Two or three years ago, if you asked me what they were, I would probably have listed them as: Highest granularity &#8211; unit tests, quick to run, drive low-level class design Fragmented &#8211; integration tests, testing higher-level components [...]]]></description>
			<content:encoded><![CDATA[<p>In TDD, different styles of tests can be applied to cover different levels in your code base. Two or three years ago, if you asked me what they were, I would probably have listed them as:</p>
<ul>
<li><strong>Highest granularity</strong> &#8211; unit tests, quick to run, drive low-level class design</li>
<li><strong>Fragmented</strong> &#8211; integration tests, testing higher-level components and external dependencies (e.g. real SQL database, fake message bus)</li>
<li><strong>Whole system at once</strong> &#8211; slow end-to-end tests, testing for story/feature acceptance at the UI or client API level</li>
</ul>
<p>However, it has become increasingly clear that fragmented integration tests (somewhere in the middle between unit and full-blown end-to-end integration tests) don&#8217;t really provide the same value as their brothers.</p>
<p>They suffer all the disadvantages of both unit <em>and</em> end-to-end tests:</p>
<ul>
<li>Like unit tests, they require setting up mocks/test doubles for collaborating modules</li>
<li>Like end-to-end tests, they have a high cost of maintaining external components like databases and integrated third party systems (setting them up, populating them with the right test data, reverting changes for next time etc)</li>
<li>Like unit tests, they are brittle and not friendly to refactoring</li>
<li>Like end-to-end tests, they are slow to run</li>
</ul>
<p>&#8230; and, over the lifetime of the code base, the only real benefit they provide is slightly faster feedback of problems than end-to-end tests. Is it really worth keeping them?</p>
<img src="http://feeds.feedburner.com/~r/RichardDingwall/~4/1DOKUBw5BBE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://richarddingwall.name/2011/05/14/fragmented-integration-tests-aka-the-questionable-value-zone/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://richarddingwall.name/2011/05/14/fragmented-integration-tests-aka-the-questionable-value-zone/</feedburner:origLink></item>
		<item>
		<title>NHibernate session management and WCF, redux</title>
		<link>http://feedproxy.google.com/~r/RichardDingwall/~3/EcMcscUWVKs/</link>
		<comments>http://richarddingwall.name/2011/04/22/nhibernate-session-management-and-wcf-redux/#comments</comments>
		<pubDate>Thu, 21 Apr 2011 23:38:02 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[Castle Windsor]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://richarddingwall.name/?p=4396</guid>
		<description><![CDATA[It&#8217;s been nearly a year since I published my method for getting one NHibernate session per WCF operation using Castle&#8217;s NHibernate Facility and AutoTx AOP Facility &#8212; a method I developed for an application which was having serious session management issues (it was using one session per SQL statement). However, today I ripped it all [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s been nearly a year since I published my method for getting <a href="http://richarddingwall.name/2010/08/17/one-nhibernate-session-per-wcf-operation-the-easy-way/">one NHibernate session per WCF operation</a> using Castle&#8217;s NHibernate Facility and AutoTx AOP Facility &#8212; a method I developed for an application which was having serious session management issues (it was using one session per <em>SQL statement</em>). However, today I ripped it all out.</p>
<p>The method itself still works. There&#8217;s nothing wrong with it. As long as you&#8217;re only doing one session per WCF operation (or one session per ASP.NET MVC request for that matter), it works great. However, problems arise when you mix <em>other</em> session styles.</p>
<p>For example, our application has a series of long-running background threads for processing jobs on a queue (up to an hour each) &#8212; as well as synchronous WCF operations &#8212; all requiring NHibernate. In this case, the one-size-fits-all approach using AOP and the container simply couldn&#8217;t give us the control we needed over each session&#8217;s lifetime, so we removed the Facility from our Windsor container, and instead now do:</p>
<ul>
<li>Register the ISessionFactory in the container, singleton scoped.</li>
<li>Inject ISessionFactory and call <code>ISessionFactory.OpenSession()</code>, <code>ISession.BeginTransaction()</code> and <code>ITransaction.Commit()</code> at outer boundaries of your application (e.g. WCF service implementations), and background jobs executing outside the context of a WCF operation.</li>
<li>Pass ISession down through your application as a parameter into any methods that access the database. Callees must not hold any reference to it, or try to manage its lifestyle (e.g. closing it, opening their own transactions etc).</li>
</ul>
<p>(Note: all NHibernate calls are wrapped in a transaction and committed. Even if they are only SELECT statements, it&#8217;s <a href="http://nhprof.com/Learn/Alerts/DoNotUseImplicitTransactions">still a good practice</a>.)</p>
<p>It has more-or-less the same end effect as AutoTx facility and CallContext-scoped SessionManager, but with the added control of being able to explicitly manage session lifetimes in other situations. It&#8217;s a few more lines of code, but it&#8217;s also a good example of stop trying to hide your ORM, and <a href="http://ayende.com/Blog/archive/2011/03/16/architecting-in-the-pit-of-doom-the-evils-of-the.aspx">just embrace the ISession directly</a>. And a reminder that technical solutions are never infallible, no matter how elegant they might seem.</p>
<img src="http://feeds.feedburner.com/~r/RichardDingwall/~4/EcMcscUWVKs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://richarddingwall.name/2011/04/22/nhibernate-session-management-and-wcf-redux/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://richarddingwall.name/2011/04/22/nhibernate-session-management-and-wcf-redux/</feedburner:origLink></item>
		<item>
		<title>Strange CLR behavior</title>
		<link>http://feedproxy.google.com/~r/RichardDingwall/~3/-R107NtOMso/</link>
		<comments>http://richarddingwall.name/2011/04/21/strange-clr-behavior/#comments</comments>
		<pubDate>Thu, 21 Apr 2011 14:19:44 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://richarddingwall.name/?p=4368</guid>
		<description><![CDATA[Here&#8217;s a little CLR brain teaser for you: A method is throwing a NullReferenceException. The stack trace indicates it is originating on a line that has only a closing curly brace on it (i.e. }). How could this be explained? Note that: The code is not optimized. The PDB file is the correct version. The [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a little CLR brain teaser for you:</p>
<p><strong>A method is throwing a NullReferenceException. The stack trace indicates it is originating on a line that has only a closing curly brace on it (i.e. <code>}</code>). How could this be explained?</strong></p>
<p>Note that:</p>
<ol>
<li>The code is not optimized.</li>
<li>The PDB file is the correct version.</li>
<li>The method has no <code>using</code> statements.</li>
<li>There is no code generation or reflection happening.</li>
</ol>
<p>Stumped? Okay, here&#8217;s a simple case to reproduce it.</p>
<pre class="brush: csharp; title: ; notranslate">void Test()
{
    try
    {
        (null as string).ToLower();
    }
    catch
    {
        throw;
    }
}</pre>
<p>If you said this code reports a NullReferenceException on line 5, you&#8217;d be <strong>wrong</strong>. The CLR reports it coming from line 11. Weird, huh? It seems to be something about rethrowing unwrapped NullReferenceExceptions, either as <code>throw</code> or <code>throw e</code>. If I <code>throw new Exception("...", e)</code> it works as expected.</p>
<p>Anyone care to hazard an explanation for this behaviour?</p>
<p>A <a href='http://richarddingwall.name/wp-content/uploads/2011/04/LineNumberBug.zip'>reference test case is available here</a>, with <a href='http://richarddingwall.name/wp-content/uploads/2011/04/output.txt'>observed output here</a>. (Compiling under Any CPU, .NET 4 in Debug configuration in VS2010 SP1.)</p>
<img src="http://feeds.feedburner.com/~r/RichardDingwall/~4/-R107NtOMso" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://richarddingwall.name/2011/04/21/strange-clr-behavior/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://richarddingwall.name/2011/04/21/strange-clr-behavior/</feedburner:origLink></item>
		<item>
		<title>The road to automated database deployment</title>
		<link>http://feedproxy.google.com/~r/RichardDingwall/~3/P4mWHAXPd2o/</link>
		<comments>http://richarddingwall.name/2011/02/09/the-road-to-automated-database-deployment/#comments</comments>
		<pubDate>Wed, 09 Feb 2011 21:03:15 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Deployment]]></category>
		<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false">http://richarddingwall.name/?p=4246</guid>
		<description><![CDATA[Working in an agile team means delivering software early and often &#8212; several times a day even. The only way to achieve this without going crazy doing releases all the time is to eliminate all the manual steps in your release process, until you&#8217;re leave with a single mouse-click to get your code into to [...]]]></description>
			<content:encoded><![CDATA[<p>Working in an agile team means delivering software early and often &#8212; several times a day even. The only way to achieve this without going crazy doing releases all the time is to eliminate all the manual steps in your release process, until you&#8217;re leave with a single mouse-click to get your code into to production.</p>
<p>One of the biggest challenges here is how to handle your app&#8217;s back-end database. Application files can be deleted and restored in seconds, websites rolled and and replaced a thousand times, but the database is a living, breathing beast, closely guarded by a separate team of DBAs who usually won&#8217;t even let you see what state its in, let alone make changes. If you screw up a database script, it could cost hours of downtime restoring from a backup. So how do you automate changes then? Here&#8217;s how we did it on a recent project.</p>
<h4>Pre-requisite #1: portable script shipping</h4>
<p>I&#8217;ll never forget the deployment process on my first major commercial project. During development, everyone shared a &#8216;working copy&#8217; database, directly adding columns and tables via GUI tools. On release day, a designated person would open up <a href="http://www.red-gate.com/products/sql-development/sql-compare/">SQL Compare</a>, connect to the dev database, connect to the live database, and generate a script copying all the changes from dev to production.</p>
<p>Needless to say, this was a fairly sub-optimal solution. Here&#8217;s some of the problems we developers incurred on a regular basis:</p>
<ul>
<li>The diff scripts only work between specific database versions. If UAT was on a faster development cycle than PROD, we couldn&#8217;t use the same scripts between them.</li>
<li>Only the final diff script was put in source control, so if the development database crashed or was accidentally wiped in between release cycles, we lost all our changes.</li>
<li>SQL Compare can reverse-engineer schema changes, but it can&#8217;t reverse-engineer data changes/migration between tables. It&#8217;s not even a complete solution.</li>
</ul>
<p>The last one was the real nail in the coffin for us. If you already have to script data changes by hand&#8230; why not go the whole hog and do ALTER/CREATE statements too? That way you can just check in each change as a separate sql script into source control &#8212; numbered, so you know which order they go in. No more generating scripts, no more losing our work in the dev database. No more SQL Compare.</p>
<h4>Pre-requisite #2: database version tracking table</h4>
<p>Given a live database and a stack of SQL scripts, how do you know which ones need to be run? You could start reading going through them, statement by statement, until you find a change that doesn&#8217;t appear to be applied and start there &#8212; or you could simply have each script write a row to the end of a changelog table like <a href="http://blog.cherouvim.com/a-table-that-should-exist-in-all-projects-with-a-database/">this</a>:</p>
<pre class="brush: sql; title: ; notranslate">ALTER TABLE ...;
DROP TABLE ...;
-- other DDL changes

INSERT INTO CHANGELOG (16, '0016_customer_info.sql', GETDATE(), USER);</pre>
<p>That way, it becomes trivial to find out what scripts have run/need to be run against a database. And putting the special INSERT at the end of each change script ensures it doesn&#8217;t add a row unless all previous statements executed successfully.</p>
<h4>Pre-requisite #3: database version awareness</h4>
<p>When is increasing coupling in your application a good thing? When it&#8217;s between the database schema version, and the application running over the top. Your physical data model and application&#8217;s persistence model (ORM mappings etc) have to move in lockstep, so it&#8217;s a good idea to refuse to start if the database version isn&#8217;t correct.</p>
<p>You can do this quite easily by checking the highest-run script number in the CHANGELOG table, or introducing a separate VERSION table. Whatever the strategy used, a loud error on startup is much easier to diagnose than messy runtime errors when a column is missing (fail-fast).</p>
<h4>Pre-requisite #4: script privileges</h4>
<p>To make our lives easier, we introduced a new rule: all change scripts must be able to be run under the same database user/privileges as the application itself. This means we can use the application&#8217;s own connection string to run scripts, and eliminates the need for DBAs or sharing the database administrator password.</p>
<p>Running scripts with the application account means we have to grant our services rights to create and modify tables, views, stored procedures etc (i.e. Oracle&#8217;s <a href="http://www.relidb.com/oracle-resource-role/">RESOURCE</a> or MS SQL&#8217;s <a href="http://msdn.microsoft.com/en-us/library/ms190667.aspx">db_ddladmin</a> role).  Before you freak out about applications running with elevated privileges, please remember one, this is not a shared database &#8212; it&#8217;s for exclusive use of our application, there is only one user &#8212; and two, this application does not run on desktops, so there is no risk of users uncovering credentials and logging in themselves.</p>
<p>This is the same self-upgrading database model WordPress uses, and we justified that if it&#8217;s good enough for the 12 million WordPress sites out there on the greater Internet, then it&#8217;s good enough for one little Windows Service running in a locked-down server network.</p>
<p>Anyway. If a script <em>does</em> requires system privileges to run, it probably means it has something to do with storage or security &#8212; e.g. storage files or table partitioning &#8212; that isn&#8217;t actually required for the application to run and thus doesn&#8217;t need to be part of the official database version history. Those scripts can thus be run independently of the automatic-upgrade process, as required by DBAs.</p>
<h4>Pre-requisite #5: clean up existing installations</h4>
<p>We have a number of copies of our applications running in the wild, in various states of disrepair. Scripts that were never run, or ran with &#8216;continue on error&#8217; enabled, and ad hoc customizations by DBAs, and missing entries from the CHANGELOG table all needed to be smoothed over to make a solid platform before any automated process can take over. In this case, we did it by hand (ironically using SQL Compare), but depending on the number of installations out there, and effort required, you may wish to incorporate these clean up steps in your automated scripts.</p>
<h4>End goal: self-upgrading application</h4>
<p>From this point, it&#8217;s relatively easy to implement an automated upgrade process that checks the CHANGELOG table to find out which scripts haven&#8217;t been run yet, and run them. That way it works against <em>any</em> previous database version. Our upgrader tool also performs a number of prepatory and clean-up steps, such as creating the CHANGELOG table if required, and cleaning up any vestigal remains of the previous database deployment process.</li>
<p>This process can be designed, and unit tested, and audited to a greater degree than any human process could ever achieve. You can run it hundreds of times over to tweak it, and test it against all sorts of different database configurations with minimal effort. It can and should become part of your continuous integration and automated build and tests.</p>
<h4>Failure and backups</h4>
<p>Unfortunately, even with all the extra confidence you get from scripting, there is always a risk of something going wrong on release day. One part of the manual process we&#8217;re missing is backups, so we&#8217;re currently looking into to add an automated backup step before kicking off (probably a lightweight one, using something like a <a href="http://msdn.microsoft.com/en-us/library/ms175158.aspx">Snapshot</a> in MS SQL or <a href="http://download.oracle.com/docs/cd/B28359_01/appdev.111/b28424/adfns_flashback.htm">Flashback</a> in Oracle). That way, we can eventually aim to provide automatic rollback capabilities in the event a script fails.</p>
<h4>Final words</h4>
<p>I&#8217;m not saying that the ours is the only way of achieveing automated database deployment, or that this is neccessarily the best way. We&#8217;re still working out the kinks, but I&#8217;d say it&#8217;s looking pretty good so far.</p>
<img src="http://feeds.feedburner.com/~r/RichardDingwall/~4/P4mWHAXPd2o" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://richarddingwall.name/2011/02/09/the-road-to-automated-database-deployment/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		<feedburner:origLink>http://richarddingwall.name/2011/02/09/the-road-to-automated-database-deployment/</feedburner:origLink></item>
		<item>
		<title>The Fat ViewModel</title>
		<link>http://feedproxy.google.com/~r/RichardDingwall/~3/lmS7-XKlH3g/</link>
		<comments>http://richarddingwall.name/2010/12/08/the-fat-viewmodel/#comments</comments>
		<pubDate>Wed, 08 Dec 2010 16:10:59 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Anti-Patterns]]></category>
		<category><![CDATA[featured]]></category>

		<guid isPermaLink="false">http://richarddingwall.name/?p=3997</guid>
		<description><![CDATA[If someone asked you, what are the building blocks of MVVM, what would you say? Models, Views, and ViewModels, of course. It&#8217;s in the name. But really, there are two others: Models Views ViewModels Commands Events If Commands and Events aren&#8217;t strongly represented in your application, I&#8217;d say there is a strong chance it isn&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p>If someone asked you, what are the building blocks of MVVM, what would you say? <strong>Models</strong>, <strong>Views</strong>, and <strong>ViewModels</strong>, of course. It&#8217;s in the name. But really, there are two others:</p>
<ul>
<li>Models</li>
<li>Views</li>
<li>ViewModels</li>
<li><strong>Commands</strong></li>
<li><strong>Events</strong></li>
</ul>
<p>If Commands and Events aren&#8217;t strongly represented in your application, I&#8217;d say there is a strong chance it isn&#8217;t factored very well.</p>
<p>One problem I see quite often is the <strong>Fat ViewModel</strong>: a long, bloated class that violates SRP by presenting complex application Commands to the view, and implementing them too.</p>
<h4>Symptoms</h4>
<p>You can tell you have a Fat ViewModel if any of the following are true:</p>
<ul>
<li>Instead of having a separate class for each Command, your ViewModel uses DelegateCommands (aka RelayCommands) to invoke methods on itself.</li>
<li>Your ViewModel has three properties, two commands, and is 300 lines long.</li>
<li>Your ViewModel has a large number of services injected into it.</li>
<li>Your ViewModel tests include assertions for both presentation <em>and</em> application behaviour.</li>
<li>Testing simple UI behaviour &#8212; e.g. a button should be disabled after it has been clicked &#8212; requires excessive mocking of dependencies.</li>
<li>Your ViewModel tests frequently call xyzCommand.Execute().</li>
<li>Commands cannot easily be re-used by other ViewModels. Your application is not modular.</li>
<li>ViewModels update their state directly, instead of listening for <a href="http://codebetter.com/blogs/jeremy.miller/archive/2007/06/29/build-your-own-cab-11-event-aggregator.aspx">global application Events</a>.</li>
</ul>
<p>Instead, if you extract Commands into separate classes, that publish their results via Events, you will benefit by having:</p>
<ul>
<li>Skinny and light ViewModels.</li>
<li>Commands that can be developed and tested in isolation.</li>
<li>Commands that encapsulate and mask complex logic.</li>
<li>Separation of presentation logic (ViewModels) from application logic (Commands).</li>
<li>A catalog of clearly defined and reusable Commands that be composed into new ViewModels.<br/><br/></li>
</ul>
<h4>Whither DelegateCommand?</h4>
<p>From the cases I have seen, I have no doubt that DelegateCommands are the primary cause of Fat ViewModels &#8212; they encourage developers to implement Commands using local ViewModel methods, which results in poorly-factored code. For this reason, I consider DelegateCommands to be in the same bad code smell category as ServiceLocator: as an anti-pattern, with few legitimate uses. (One is when the Command is entirely self-contained within the ViewModel (i.e. does not collaborate with any other object), the other when genuinely delegating to another object. But in that case, the other object should probably be a Command anyway.)</p>
<p>See also: <a href="http://codebetter.com/blogs/ian_cooper/archive/2008/12/03/the-fat-controller.aspx">Fat Controller</a>, <a href="http://en.wikipedia.org/wiki/God_object">God Object</a>.</p>
<img src="http://feeds.feedburner.com/~r/RichardDingwall/~4/lmS7-XKlH3g" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://richarddingwall.name/2010/12/08/the-fat-viewmodel/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		<feedburner:origLink>http://richarddingwall.name/2010/12/08/the-fat-viewmodel/</feedburner:origLink></item>
	</channel>
</rss>

