<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>the tar pit</title>
	<atom:link href="http://blog.goneopen.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.goneopen.com</link>
	<description>Thrashing around in the stickiness of software</description>
	<lastBuildDate>Wed, 11 Apr 2012 04:41:25 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4.1</generator>
		<item>
		<title>Android Running slow on Phone and Messages</title>
		<link>http://blog.goneopen.com/2012/04/android-running-slow-user-dictionary/</link>
		<comments>http://blog.goneopen.com/2012/04/android-running-slow-user-dictionary/#comments</comments>
		<pubDate>Wed, 11 Apr 2012 04:41:24 +0000</pubDate>
		<dc:creator>todd</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.goneopen.com/?p=376</guid>
		<description><![CDATA[I just spent the weekend trying to fix my Android (HTC Sensation). It was running so slow that I got to a point that I could phone out, pick up my phone or write text messages. My battery life was under 2 hours. How bad is that? Actually, I then found that I had a [...]]]></description>
			<content:encoded><![CDATA[<p>I just spent the weekend trying to fix my Android (HTC Sensation). It was running so slow that I got to a point that I could phone out, pick up my phone or write text messages. My battery life was under 2 hours. How bad is that? Actually, I then found that I had a similar problem on my mac when using Thunderbird. The solution was simple enough. </p>

<p>I had 20,000 contacts between my various accounts. There is then a practical limit of contacts on my Android &#8211; even when I got it down to 5,000 I was still finding problems.</p>

<p><strong>Symptoms:</strong> Low battery life, high <span class="caps">CPU </span>usage, unresponsive Messages and Phone app.<br />
Diagnosis: </p>

<p> # Open task manager. You should see User Dictionary using a high level of <span class="caps">CPU </span>%.<br />
 # Open People application. Select View. You should see a high level of contacts.</p>

<p><strong>Simple solution:</strong> have less contacts.</p>

<p><strong>Actual problem:</strong> I have multiple google accounts (personal and couple of work accounts). Somehow two accounts had replicated some users 5,000 times! That is, I have 19,500 too many contacts. It appears to be the joy of Google+ (which I have never wanted in the first place).</p>

<p><strong>Solution:</strong> Remove all duplicate users (in this case my contacts were perhaps corrupted because google couldn&#8217;t detect any duplicates). That&#8217;s right, I had to delete/merge 19,500 contacts 250 contacts a time. Then I had to make sure that I didn&#8217;t resync either my Thunderbird or Android.</p>

<p>End result. A working Android, a working Thunderbird and a day of my life lost.</p>

<p><strong>Note:</strong> I actually did a factory reset which I didn&#8217;t need to do. What I also now have is a very nicely ordered contact list and I know that my backup is working.</p>]]></content:encoded>
			<wfw:commentRss>http://blog.goneopen.com/2012/04/android-running-slow-user-dictionary/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Kanban Simulator</title>
		<link>http://blog.goneopen.com/2012/02/kanban-simulator/</link>
		<comments>http://blog.goneopen.com/2012/02/kanban-simulator/#comments</comments>
		<pubDate>Sun, 12 Feb 2012 02:29:02 +0000</pubDate>
		<dc:creator>todd</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.goneopen.com/2012/02/kanban-simulator/</guid>
		<description><![CDATA[I have decided to release out into the wild a kanban simulator. It&#8217;s been a long time in the making and really I&#8217;m wondering what to use it for! It started out as a project to think through (a) some of the calculations and relationships in a kanban system and (b) a single-page, javascript application. [...]]]></description>
			<content:encoded><![CDATA[<p>I have decided to release out into the wild a kanban simulator. It&#8217;s been a long time in the making and really I&#8217;m wondering what to use it for!</p>

<p>It started out as a project to think through (a) some of the calculations and relationships in a kanban system and (b) a single-page, javascript application. With the later, it has been a great exercise. I have found the <a href="http://requirejs.org/docs/whyamd.html"><span class="caps">AMD </span>and requirejs</a> to be a great solution. I combined it with building via <a href="http://nodejs.org/">node.js</a> and did <a href="http://pivotal.github.com/jasmine/">test-first in jasmine</a>. My last results from jasmine are: <code>131 specs, 0 failures in 4.8s</code>. </p>

<p>Anyway, this is a kanban board simulator that allows you to setup a board and then run tasks through and look at metrics.</p>


<ul>
<li>An overview of <a href="http://prezi.com/31b6jssbqwsi/kanban-simulator/">how to use the simulator is here</a></li>
<li>A <a href="http://kanban.goneopen.com">running simulator is here</a></li>
<li>Download binaries to run your own version and make configuration changes <a href="http://kanban.goneopen.com/simulator.zip">from here</a></li>
</ul>



<p>I&#8217;m wondering if it has any use as a training mechanism. Trainers could get participants to generate and run their own data. I haven&#8217;t written up instructions on changing the configuration but if you download the code and update the <code>scripts/config/simple-board.js</code> file you might get the hang of it. You&#8217;ll also see that I have created a small <span class="caps">DSL </span>for creating &#8220;Team practices&#8221; but that&#8217;s another story.</p>]]></content:encoded>
			<wfw:commentRss>http://blog.goneopen.com/2012/02/kanban-simulator/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pair programming: some good reminders</title>
		<link>http://blog.goneopen.com/2012/01/pair-programming-some-good-reminders/</link>
		<comments>http://blog.goneopen.com/2012/01/pair-programming-some-good-reminders/#comments</comments>
		<pubDate>Mon, 09 Jan 2012 23:26:28 +0000</pubDate>
		<dc:creator>todd</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.goneopen.com/2012/01/pair-programming-some-good-reminders/</guid>
		<description><![CDATA[I have been lucky enough to have a pairing session with a very experienced programmer lately. In my day job, I pair all the time. But it is usually with experienced, yet resistant programmers and very rarely is it rewarding for me. This experience has been the opposite and a good reminder of why I [...]]]></description>
			<content:encoded><![CDATA[<p>I have been lucky enough to have a pairing session with a very experienced programmer lately. In my day job, I pair all the time. But it is usually with experienced, yet resistant programmers and very rarely is it rewarding for me. This experience has been the opposite and a good reminder of why I do like pairing and want to do more of it collegially. Usually, I am pairing either as the experienced half or a coach but rarely on equal(-ish) footing. What a treat! Some background, we have been writing a graph database in Scala and are now four days in &#8211; I usually write line-of-business applications rather than tool libraries. We started with a list of features (XP style) and we have been <span class="caps">TDD</span>ing, test-first all of the code. We also have been using a <span class="caps">BDD</span>-style Given/When/Then style test suite in JUnit. Mostly we have been mocking with occasional classical-TDD assertions and one fake implementation.</p>

<p>Here are some notes to myself that are related between pairing itself and problems we discussed.</p>

<h3>Technical debt still grows quickly</h3>

<p>We just spent most of day four dealing with the decisions to move on. I couldn&#8217;t believe how many issues where in the code that we had marked <span class="caps">TODO </span>which at the time allowed us to move on. Each small decision (if I remember correctly) was very good at the time but to have some of these come and bite us by day four was amazing. Note to myself we should actually have a running count of the number of <span class="caps">TODO</span>s and graph it or put some upper limit.</p>

<h3>Be careful about code (and domain concepts) not integrated into core</h3>

<p>This is probably my greatest learning and reminder. Hopefully, I can explain. There was a point that we decided to write the code that serialised byte arrays to disk. Neither of us had a working knowledge of the libraries needed so we decided to reduce risk in this area. We effectively spiked this code albeit with tests. It was all production-ready code. However, it was integrated into the core code base. We called this programming on a leaf domain concept &#8211; maybe orphaned leaf might be more appropriate. The leaf is on the outer of the domain concepts. To make this more concrete, the core manages all the nodes and relationships in the database, then we manage persistence and flushing and finally out on the ends we read/write to disk. We working on the disk read/write and yet hadn&#8217;t integrated into the persistence code that would call it. The problem was that as we started to add functionality to the code code, the leaf code became hard to work with. In the end we treated the original leaf code as a spike and coded from the core to integrate the leaf. I think this is closer to the style of <span class="caps">GOOS.</span></p>

<h3>Pairing changes the rhythm (and rhyme) of the day</h3>

<p>The rhythm is generally evenly paced throughout the day &#8211; often it feels slow and plodding. Rarely, do I quite get the excitement of individual programming when I feel on a roll whacking out the code &#8211; but neither do we get the lows and stagnation. Instead, there is much discussion, whiteboarding and mostly the coding revolves around writing the tests (particular with mocks spelling out the interactions and responsibilities). We ping-ponged between test writing for one person and then the other passing the test and starting the next failed test before handing back to the other person to pass the tests and start all over (with refactoring on green by either). Our day was between 6 and 10 elapsed hours with an hour off for lunch. It was sustained, engaging work. At the end of the day we were surprised how many features were ticked off. Slow and steady was the rhyme;Ping-pong, red-green-refactor was the rhythm.</p>

<h3>Domain confusions are still the biggest wasters of time</h3>

<p>Our biggest waster was not knowing how to do something and this was worst when we had confusions already existing in the code. Particularly on day four we had to refactor them out of the code. We made best progress when we had an even understanding between us &#8211; and this occurred when we had concrete examples mapped out on the whiteboard (specification by example). So I&#8217;m still not worried about productivity arguments about doubling up in pairing &#8211; that might be the case with trivial implementations </p>

<h3>Deal with complexity through examples to build simplicity in implementation</h3>

<p>Complexity here is the interaction (and side effects) between parts of system. We did too much of this through discussion and holding ideas in our head and trying to isolate complexity through separation and encapsulation. For example, a test might isolate the caching and dirty-tracking mechanism for nodes but often to understand that it was talked about in a wider context. I think that we could have used examples that work through the system to encapsulate the complexity rather than keep it limited to our discussions. This sounds to me that it is a mixture of specification by example and <span class="caps">GOOS</span>-style tests. Sorry if that isn&#8217;t very clear. </p>

<h3>Live with your own confusions and ambiguity but be careful about letting them into the code base</h3>

<p>These are related to above. There were times that I was willing to live with ambiguity and confusion and my pairing partner knew what he was doing &#8211; so why wouldn&#8217;t I go with the flow?! A couple of these places turned out to be poor abstractions that took us time to refactor. Perhaps, I will be bolder next time. I think I would insist on more concrete end-to-end examples (rather than simply tests)<br />
h3. Multiple assertions in a test</p>

<p>Because we are using mocks, of course, there are always multiple assertions. Nonetheless, we always had to ensure that we were describing what the system did and focus on one aspect. But this was just a good reminder asserting a single thing is not the same as only making one assertion. The code was more readable and in fact we spent time wrapping jmock to get readable, concise assertions.</p>

<h3>Symmetry-style tests are a really useful type of test</h3>

<p>I haven&#8217;t explicitly used symmetry-style tests within one test before. I usually do across a test class. In our case, we needed to serialise and deserialise byte-arrays of datas (numbers, strings, properties). Usually, I would separate out these tests (also one per class and here we had a reader and writer) and then combine using a Setup. We just put them in the same test, it was far more readable and appropriate to the level of complexity of the task</p>

<h3>Fake implementations are markers for debt and rework</h3>

<p>I often use fake, concrete implementations in tests to get me going. I see them as a way to keep moving. We were acutely reminded that they are debt in the system. We found that in the implementation had gone too far and we used it in more than one test class. As such, we we came to take it out it touched a number of tests that we needed to refactor. It had also stopped us seeing some assumptions. The note to myself is to make sure that such implementations are private to the tests.</p>

<h3>CI &amp; source control even for the single-programmer environment is gonna save you</h3>

<p>Because we are working in Scala some of the <span class="caps">IDE </span>support is not quite there. We lost time without <span class="caps">CI.</span> It&#8217;s there now &#8211; well, almost</p>

<h3>Pairing with you reminds you (acutely) of accommodations you make and your own limitations</h3>

<p>Pairing is a good mirror &#8211; your get to look back at yourself some quietly and sometime not so! All those little things that I do are accentuated: the little key presses I don&#8217;t remember, the quirky naming conventions, the <span class="caps">IDE </span>features I could improve. I love the little reminders to keep improving.</p>]]></content:encoded>
			<wfw:commentRss>http://blog.goneopen.com/2012/01/pair-programming-some-good-reminders/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Effect maps</title>
		<link>http://blog.goneopen.com/2011/10/effect-maps/</link>
		<comments>http://blog.goneopen.com/2011/10/effect-maps/#comments</comments>
		<pubDate>Fri, 28 Oct 2011 20:31:25 +0000</pubDate>
		<dc:creator>todd</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[agile]]></category>
		<category><![CDATA[contracts]]></category>

		<guid isPermaLink="false">http://blog.goneopen.com/2011/10/effect-maps/</guid>
		<description><![CDATA[I just read a copy of Gojko Adic&#8217;s Agile Product Management using Effect Maps because I too still find high-level product visualisation problematic when trying to do iterative product management. Adzik explains &#8220;Effect Maps&#8221; (which are structured mind-maps) which allow for design, priorisation and scoping. It well worth the read. Here&#8217;s a few thoughts I [...]]]></description>
			<content:encoded><![CDATA[<p>I just read a copy of Gojko Adic&#8217;s <a href="http://gojko.net/effect-map">Agile Product Management using Effect Maps</a> because I too still find high-level product visualisation problematic when trying to do iterative product management. Adzik explains &#8220;Effect Maps&#8221; (which are structured mind-maps) which allow for design, priorisation and scoping. It well worth the read. Here&#8217;s a few thoughts I had while reading:</p>

<h3>Simple technique for a working meeting</h3>

<p>It brings people together and always has at its base of discussion to the business value/problem to be solved. The mindmap starts from the question of the goal: Why are we doing this? What is the desired business change? I could see structuring early discussions with senior people. Likewise, I could all stakeholders in the room and use the technique. </p>

<h3>How to get see the whole and defer ambiguity</h3>

<p>The four-levels in the mindmap is detailed enough to move through the <em>Why</em>, <em>Who</em>, <em>How</em> and then detailed <em>What</em>. But in practice, there is loads of detail still to come in the <em>What</em> (the features) that the team will need to work. Be able to defer with the implementation details to when starting on the specific is an important strategy to avoid wasteful work and delays.</p>

<h3>Good for Target Cost development-type contracts</h3>

<p>I tend to work on Target Cost contracts but always struggle with what that end goal and target cost is. Few can articulate what their break-even (or often opportunity) cost is. The effect map should provide a good way to identify needs and the potential investment required. Usually, in the end, while I might suggest a cost clients also usually have a sense of what they can afford against there (often implicit) view of its value. Interestingly, investment is the correct vernacular over cost. Most of my clients want to capitalise my work rather than pay for it out of operational budget.</p>

<h3>Avoids lists of stories</h3>

<p>If you really wanted to get me started of a rant then start sputing that user stories are <strong>the</strong> technique to counter requirements documents. In my experience, this assumption always leads you back to the same root-cause analysis: the analysis wasn&#8217;t refined enough (ie the story was too big, not well defined, could have been broken-up more). Although all those reasons are true, I tend to see that there wasn&#8217;t enough context because the stories while grouped (into themes) they really didn&#8217;t have good prioritisation, scoping at a higher level. Or as he puts it, user stories are being used for managing long-term release planning. The effect map helps by not using the user stories at level. This is nice because it keeps in the front of our mind that user stories are a merely rubric, albeit a very useful one. The effect helps us keep user stories at the outmost leaves of the map and not toward the root. As he says,</p>

<blockquote><p>User stories are de facto standard today for managing long term release planning. This often includes an &#8220;iteration zero&#8221;, a scoping exercise or a user story writing workshop at the start of a milestone. During the &#8220;iteration zero&#8221; key project sponsors and delivery team together come up with an initial list of user stories that will be delivered. A major problem with the &#8220;iteration zero&#8221; approach is the long stack of stories that have to be managed as a result of it. Navigating through hundreds of stories isn&#8217;t easy. When priorities change, it is hard to understand which of the hundreds of items on the backlog are affected. Jim Shore called this situation &#8220;user story hell&#8221; during his talk at Oredev 2010, citing a case of a client with 300 stories in an Excel spreadsheet. I&#8217;ve seen horror stories like that, perhaps far too often.</p></blockquote>]]></content:encoded>
			<wfw:commentRss>http://blog.goneopen.com/2011/10/effect-maps/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Having Jasmine tests results in TeamCity via node.js (on windows) invoked from powershell</title>
		<link>http://blog.goneopen.com/2011/09/having-jasmine-tests-results-in-teamcity-via-node-js-on-windows-invoked-from-powershell/</link>
		<comments>http://blog.goneopen.com/2011/09/having-jasmine-tests-results-in-teamcity-via-node-js-on-windows-invoked-from-powershell/#comments</comments>
		<pubDate>Mon, 26 Sep 2011 03:47:52 +0000</pubDate>
		<dc:creator>todd</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[CI]]></category>
		<category><![CDATA[jasmine]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[node]]></category>
		<category><![CDATA[nodejs]]></category>
		<category><![CDATA[teamcity]]></category>

		<guid isPermaLink="false">http://blog.goneopen.com/2011/09/having-jasmine-tests-results-in-teamcity-via-node-js-on-windows-invoked-from-powershell/</guid>
		<description><![CDATA[I test my javascript code via jasmine on a windows machine. I primarily write jquery-plugin-style code. Now I need to get this onto CI. A colleague I worked with took my test strategy in jasmine and wrote a library to run it very quickly on node.js. There are other places showing how to integrate with [...]]]></description>
			<content:encoded><![CDATA[<p>I test my javascript code via jasmine on a windows machine. I primarily write jquery-plugin-style code. Now I need to get this onto <span class="caps">CI.</span> A colleague I worked with took my test strategy in jasmine and wrote a library to run it very quickly on node.js. There are other places showing how to integrate with TeamCity and <a href="http://benshepheard.blogspot.com/2011/05/running-jasmine-tests-in-continuous.html">Jasmine with JsTestDriver</a> or <a href="http://joseoncode.com/2011/08/09/running-qunit-tests-in-teamcity/">Qunit</a> and also the documentation on how to easily <a href="http://confluence.jetbrains.net/display/TCD65/Build+Script+Interaction+with+TeamCity#BuildScriptInteractionwithTeamCity-ImportingXMLReports">integrate service messages with TeamCity</a>.</p>

<p>One caveat: I am not wanting to test cross-browser functionality. Therefore, I don&#8217;t need or want a browser or the associated slowness and the brittleness of cross-process orchestration. (Note: I have tried to stabilise these types of tests using NUnit and <span class="caps">MST</span>est runners invoking selenium and/or watin &#8211; it gets unstable quickly and there is too much wiring up.)</p>

<p>So this approach is simple and blindly fast thanks to <a href="http://andrewpmckenzie.github.com/node-jasmine-dom/">Andrew McKenzie&#8217;s jasmine-node-dom</a> which is an extension of <a href="https://github.com/mhevery/jasmine-node">jasmine-dom</a>. He wrote his for linux and his example is with Jenkins so I have forked a <a href="http://github.com/toddb/node-jasmine-dom">version for windows</a> which has a node.exe binary which is available form <a href="http://nodejs.org/#download">node.js</a>.</p>

<p>Anyway, this blog covers the powershell script to invoke the <code>jasmine-node-dom</code> and publish it to <code>TeamCity</code>.</p>

<p>Here&#8217;s the script:</p>

<h2>build.ps1 (or directly in TeamCity)</h2>



<pre class="brush:ps">
	
	$node_dir = &quot;node-jasmine-dom\bin&quot;	

	&amp; &quot;$node_dir\node.exe&quot; &quot;$node_dir\jasmine-dom&quot; `   
				--config tests.yaml `
				--format junit `
				--output javascript-results.xml 

	write-host &quot;##teamcity[importData type='junit' path='javascript-results.xml']&quot;    
	
</pre>



<p>An explanation if it isn&#8217;t obvious. First let&#8217;s start with files that are needed. I have the windows <a href="http://github.com/toddb/node-jasmine-dom">node-jasmine-dom</a> installed in its own directory. I then call <code>node.exe</code> with <code>jasmine-dom</code>. That should just work all out-of-the-box. I then tell it where the manifest is that knows about the tests (<code>tests.yaml</code> &#8211; see below for example) and then I give it the results file. <code>jasmine-node-dom</code> is great because it reads the <code>SpecRunner.html</code> and reconstructs the <code>DOM</code> enough that the tests are valid.</p>

<p>Finally, I tell teamcity to read the results out of <code>junit</code>. This is very easy and I recommend that you find out what else you need to do.</p>

<h2>tests.yaml</h2>



<pre class="brush:text">
	---
	  test_one:
	    name: Example test one
	    runner: ./tests/SpecRunner.html
</pre>



<p>This <code>yaml</code> file points to the <code>Jasmine</code> runner.</p>

<p>Other points: </p>

<p> * All my jasmine tests are invoked from their own <code>SpecRunner.html</code> file by convention<br />
 * I will write a script that will automatically generate the <code>yaml</code> file<br />
 * I always put all my powershell scripts into <code>psake</code> scripts (then they can be run by the dev or the build machine)<br />
 * my code isn&#8217;t quite filed as above</p>

<h2>Summary Instructions:</h2>

<p> # download jasmine-node-dom and install in <code>tools\</code> directory<br />
 # add new <code>Task</code> to build scripts (I use <code>psake</code>)<br />
 # add a new <code>test.yaml</code> manifest (or build one each time)<br />
 # Add new <code>jasmine</code> tests via <code>SpecRunner.html</code> with your javascript<br />
 # Ensure that the build script is run via a <em>build step</em> in a <em>configuration</em> from <code>TeamCity</code><br />
 # Now you can inspect the Tests in TeamCity</p>]]></content:encoded>
			<wfw:commentRss>http://blog.goneopen.com/2011/09/having-jasmine-tests-results-in-teamcity-via-node-js-on-windows-invoked-from-powershell/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Sharepoint &amp; TDD: Getting started advice</title>
		<link>http://blog.goneopen.com/2011/07/sharepoint-tdd-getting-started/</link>
		<comments>http://blog.goneopen.com/2011/07/sharepoint-tdd-getting-started/#comments</comments>
		<pubDate>Thu, 30 Jun 2011 23:19:44 +0000</pubDate>
		<dc:creator>todd</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[CI]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[jsspec]]></category>
		<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[test automation pyramid]]></category>

		<guid isPermaLink="false">http://blog.goneopen.com/2011/07/sharepoint-tdd-getting-started/</guid>
		<description><![CDATA[I have a couple of people asking lately about starting on SharePoint. They&#8217;ve asked about how to move forward with unit and integration testing and stability. No one wants to go down the mocking route (typemock, pex and moles) and quite rightly. So here&#8217;s my road map: The foundations: Hello World scripted and deployable without [...]]]></description>
			<content:encoded><![CDATA[<p>I have a couple of people asking lately about starting on SharePoint. They&#8217;ve asked about how to move forward with unit and integration testing and stability. No one wants to go down the mocking route (<code>typemock</code>, <code>pex and moles</code>) and quite rightly. So here&#8217;s my road map:</p>

<h2>The foundations: Hello World scripted and deployable without the <span class="caps">GUI</span></h2>


<ol>
<li>Get a Hello World SharePoint &#8220;app&#8221; &#8211; something that is packageable and deployable as a <code>WSP</code></li>
<li>Restructure the folders of the code away from the Microsoft project structure so that the root folder has <code>src/</code>, <code>tools/</code>, <code>lib/</code> and <code>scripts/</code> folders. All source and tests are in <code>src/</code> folder. This lays the foundation for a layered code base. The layout looks like this <a href="https://github.com/toddb/msbuild-deployment-sample">sample application</a></li>
<li>Make the compilation, packaging, installation (and configuration) all scripted. Learn to use <code>psake</code> for your build scripts and <code>powershell</code> more generally (particularly against the SharePoint 2010 <span class="caps">API</span>). The goal here is that devs can build and deploy through the command line. As such, so too can the build server. I have a suggestion <a href="http://blog.goneopen.com/2010/11/sharepoint-deployment-scripting-with-powershell/">here</a> that still stands but I need to blog on improvements. Most notably, not splitting out tasks but rather keeping them in the same <code>default.ps</code> (because <code>-docs</code> works best). Rather than get reuse at the <code>task</code> level do it as functions (or cmdlets). Also, I am now moving away from the mix with <code>msbuild</code> that I blogged <a href="http://blog.goneopen.com/2010/11/sharepoint-deployment-packaging/">here</a> and am moving them into powershell. There is no real advantage other than less files and reduced mix of techniques (and lib inclusions).</li>
<li>Create a build server and link this build and deployment to it. I have been using <span class="caps">TFS </span>and TeamCity. I recommend TeamCity but <span class="caps">TFS </span>will suffice. If you haven&#8217;t created Build Definitions in <span class="caps">TFS</span> Workflow allow days-to-weeks to learn it. In the end, but only in the end, it is simple. Becareful with <span class="caps">TFS, </span>the paradigm here is that build server does tasks that devs don&#8217;t. It looks a nice approach. I don&#8217;t recommend it and there is nothing here by design that makes this inevitable. In <span class="caps">TFS, </span>you are going to need to build two build definitions: <code>SharePointBuild.xaml</code> and <code>SharePointDeploy.xaml</code>. The build is a compile, package and test. The deploy simply deploys to an environment &#8211; Dev, Test, Pre-prod and Prod. The challenge here is to work out a method for deploying into environments. In the end, I wrote a simple self-host windows workflow (<code>xamlx</code>) that did the deploying. Again, I haven&#8217;t had time to blog the sample. Alternatively, you can use <code>psexec</code>. The key is that for a SharePoint deployment you must be running on the local box and the most configurations have a specific service account for perms. So I run a service for deployment that runs under that service account. </li>
</ol>



<p>Now that you can reliably and repeatably test and deploy, you are ready to write code!</p>

<h2>Walking Skeleton</h2>

<p>Next is to start writing code based on a <a href="http://blog.goneopen.com/2010/11/sharepoint-tdd-part-2-good-layering/">layered strategy</a>. What we have found is that we need to do two important things: (1) always keep our tests running on the build server and (2) attend to keeping the tests running quickly. This is difficult in SharePoint because a lot of code relates to integration and system tests (as defined by <a href="http://blog.goneopen.com/2010/08/test-automation-pyramid-review/">test automation pyramid</a>). We find that integration tests that require setup/teardown of a site/features get brittle and slow very quickly. In this case, reduce setup and teardown in the the system tests. However, I am also had a case where the integration test showed that a redesigned object (that facaded SharePoint) would give better testability for little extra work.</p>


<ol>
<li>Create 6 more projects based on a <span class="caps">DDD </span>structure (Domain, Infrastructure, Application, Tests.Unit, Tests.Integration &amp; Tests.System). Also rename your SharePoint project to <code>UI-[Your App]</code>, this avoids naming conflicts on a SharePoint installation. We want to create a <a href="http://alistair.cockburn.us/crystal/articles/hpaaa/hexagonalportsandadaptersarchitecture.htm">port-and-adapters</a> application around SharePoint. For example, we can wrap <a href="http://blog.goneopen.com/2011/05/sharepoint-tdd-part-7-repository-pattern-for-propertybag/">property bags</a> with repository pattern. This means that we create domain models (in Domain) and return them with repositories (in Infrastructure) and can test with integration tests.</li>
<li><strong>System tests:</strong> I have used <a href="http://storyq.codeplex.com/">StoryQ</a> with the team to write tests because it allows for a setup/teardown and then multiple test scenario. I could use <a href="http://www.specflow.org/">SpecFlow</a> or nBehave just as easily. </li>
<li><strong>Integration tests:</strong> these are written classical <span class="caps">TDD </span>style.</li>
<li><strong>Unit tests:</strong> these are written also classical <span class="caps">TDD</span>/BDD style</li>
<li><strong>Javascript tests</strong>: we write all javascript code using a jQuery plugin style (aka <a href="http://blog.rebeccamurphey.com/2009/10/15/using-objects-to-organize-your-code/">Object Literal</a>) &#8211; in this case, we use <a href="http://jania.pe.kr/aw/moin.cgi/JSSpec"><span class="caps">JSS</span>pec</a> (but I would now use <a href="http://pivotal.github.com/jasmine/">Jasmine</a>) &#8211; we put all tests in <code>Tests.Unit</code> but the actual javascript is still in the <code>UI-SharePoint</code> project. You will need two sorts of tests: <code>Example</code> for exploratory testing and <code>Specs</code> for the jasmine specs. I haven&#8217;t blogged about this and need to but is based on my work for writing <a href="http://plugins.jquery.com/project/jqueryplugingen">jQuery plugins with tests</a>.</li>
<li><strong>Deployment tests</strong>: these are tests that run once that application is deployed. You can go to an <span class="caps">ATOM </span>feed which returns the results of a series of tests that run against the current system. For example, we have the standard set with tells us the binary versions and which migrations (see below) have been applied. Others check whether a certain <code>wsp</code> has been deployed, different endpoints are listening, etc. I haven&#8217;t blogged this code and mean to &#8211; this has been great for testers to see if the current system is running as expected. We also get the build server to pass/fail a build based on these results.</li>
</ol>



<p>We don&#8217;t use <code>Pex and Moles</code>. We use exploratory testings to ensure that something actually works on the page</p>

<h2>Other bits you&#8217;ll need to sort out</h2>


<ul>
<li><strong>Migrations:</strong> if you have manual configurations for each environment then you&#8217;ll want to script/automate this. Otherwise, you aren&#8217;t going to be one-click deployments. Furthermore, you&#8217;ll need to assume that each environment is in a different state/version. We use <code>migratordotnet</code> with a SharePoint adapter that I wrote &#8211; it is <a href="https://github.com/toddb/migratordotnet">here for SharePoint 2010</a> &#8211; there is also a powershell runner in the source to adapt &#8211; you&#8217;ll need to download the source and compile. Migrations as an approach works extremely well for feature activation and publishing.</li>
<li><strong>Application Configuration:</strong> we use domain models for configuration and then instantiate via an infrastructure factory &#8211; certain configs require SharePoint knowledge</li>
<li><strong>Logging:</strong> you&#8217;ll need to sort of that Service Locator because in tests you&#8217;ll swap it out for Console.Logger</li>
<li><strong>WebParts:</strong> can&#8217;t be in a strongly typed binary (we found we needed another project!)</li>
<li><strong>Extension Methods to Wrap SharePoint <span class="caps">API</span></strong>: we also found that we wrapped a lot of SharePoint material with extension methods </li>
</ul>



<h2>Other advice: stay simple</h2>

<p>For SharePoint developers not used to object oriented programming, I would stay simple. In this case, I wouldn&#8217;t create code with abstractions that allowed you to unit test like <a href="http://blog.goneopen.com/2010/12/sharepoint-tdd-part-3-procedural-untestable-code/">this</a>. I found in the end the complexity and testability outweighed the simplicity and maintainability.</p>

<p>Microsoft itself has recommended the Repository Pattern to facade the SharePoint <span class="caps">API </span>(sorry I can&#8217;t for the life of me find the link). This has been effective. It is so effective we have found that we can facade most SharePoint calls in two ways:  a repository that returns/works with a domain concept or a <code>Configurator</code> (which has the single public method <code>Process()</code>).Anymore than that it was really working against the grain. All cool, very possible but not very desirable for a team which rotates people.</p>]]></content:encoded>
			<wfw:commentRss>http://blog.goneopen.com/2011/07/sharepoint-tdd-getting-started/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Repository Pattern and SharePoint to facade PropertyBag</title>
		<link>http://blog.goneopen.com/2011/05/sharepoint-tdd-part-7-repository-pattern-for-propertybag/</link>
		<comments>http://blog.goneopen.com/2011/05/sharepoint-tdd-part-7-repository-pattern-for-propertybag/#comments</comments>
		<pubDate>Mon, 23 May 2011 06:42:08 +0000</pubDate>
		<dc:creator>todd</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">http://blog.goneopen.com/2011/05/sharepoint-tdd-part-7-repository-pattern-for-propertybag/</guid>
		<description><![CDATA[Introduction Microsoft Patterns and Practices recommend the facading of SharePoint with the repository pattern. If you are an object-oriented programmer that request is straightforward. If your not then it isn&#8217;t. There are few examples of this practice and most code samples in SharePoint work directly with the API and SharePoint is scattered throughout the entire [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>

<p>Microsoft Patterns and Practices recommend the facading of SharePoint with the repository pattern. If you are an object-oriented programmer that request is straightforward. If your not then it isn&#8217;t. There are few examples of this practice and most code samples in SharePoint work directly with the <span class="caps">API </span>and SharePoint is scattered throughout the entire code base. If you haven&#8217;t read much about this there is a good section in Freeman and Pryce (Growing Object Oriented Software: Guide by Tests) about this approach &#8211; they relate this approach back to Cockburn&#8217;s ports and adapters and Evans&#8217; Anti-corruption layer. I personally think about it as an anti-corruption layer.</p>

<p>In this example, I will give two examples of how we will avoid SharePoint having too much reach into codebase when using Properties. If we were to not use this solution the case base would be very <span class="caps">EASY.</span> Whenever we want a value we would use this code snippet: <code>SPFarm.Local.Properties[key].ToString()</code> (with some <code>Security.RunWithElevatedPrivileges</code>). Using this approach, at best we are likely to see the <code>key</code> as a global constant in some register of keys.</p>

<p>This type of code does not fit the Freeman and Pryce mantra to prefer to write maintainable code over code that is easy to write. Maintainable code has separation of concerns, abstractions and encapsulation &#8211; this is also testable code. So in the end in this example, what you&#8217;ll see is a lot more code but what&#8217;ll you also hopefully appreciate is that we are teasing out domain concepts where SharePoint happens only to the technical implementation.</p>

<p>So, the quick problem domain. We have two simple concepts: a site location and an environment. We have decided that our solution requires both of these pieces of information to be stored in SharePoint. In this case, we have further decided (rightly or wrongly &#8211; possibly wrongly) that we are going to let a little bit of SharePoint leak in that both a site location and environment as really property bag values &#8211; we make this decision because the current developers think it is easier in the long run. So, we decided against the <span class="caps">EASY </span>option.</p>

<h3>Easy Option</h3>

<p>Create a register:</p>



<pre class="brush: csharp;">
public class EnvironmentKeys {
  public const string SiteLocationKey = &quot;SiteUrl&quot;;
  public const string EnvironmentKey = &quot;Environment&quot;;
}
</pre>



<p>Access it anytime either get:</p>


<pre class="brush: csharp;">
  var siteUrl = SPFarm.Local.Properties[SiteLocationKey] 
</pre>



<p>Or update:</p>


<pre class="brush: csharp;">
  SPFarm.Local.Properties[SiteLocationKey] = &quot;http://newlocation/&quot;;
  SPFarm.Local.Update();  // don't worry about privileges as yet
</pre>



<h3>Maintainable option</h3>

<p>We are going to create two domain concepts:  <code>SiteLocation</code> and <code>Environment</code> both of which are <code>PropertyBagItem</code> and that it will be fronted by a <code>PropertyBagRepository</code> that will allow us to <code>Find</code> or <code>Save</code>. Note: we&#8217;ve decided to be a little technology bound because we are using the notion of a property bag when we could just front each domain concept with respository. We can always refactor later &#8211; the other agenda here is getting SharePoint devs exposure to writing code using generics.</p>

<p>Here are our domain concepts.</p>

<p>Let&#8217;s start with our property bag item contract:</p>



<pre class="brush: csharp;">
public abstract PropertyBagItem
{
  abstract string Key { get; }
  abstract string Value { get; set; }
}
</pre>



<p>It has two obvious parts: key and value. Most important here is that we don&#8217;t orphan the key from the domain concept. This allows us to avoid the problem of a global register of keys. </p>

<p>And let&#8217;s have a new <code>SiteLocation</code> class.</p>



<pre class="brush: csharp;">
public class SiteLocation : PropertyBagItem
{
  public string Key { get { return &quot;SiteLocationKey&quot;; } }
  public string Value { get; set; }
}
</pre>



<p>Now, let&#8217;s write a test for finding and saving a <code>SiteLocation</code>. This is a pretty ugly test because it requires one being set up. Let&#8217;s live with it for this sample.</p>



<pre class="brush: csharp;">
[TestFixture]

public class PropertyBagItemRepositoryTest
{
  private PropertyBagItemRepository _repos;

  [SetUp]
  public void Setup()
  {
    _repos = new PropertyBagItemRepository();
    _repos.Save(new SiteLocation(&quot;http://mysites-test/&quot;));
  }

  [Test]
  public void CanFind()
  {
    Assert.That(_repos.Find&lt;SiteLocation&gt;().Value, Is.EqualTo(&quot;http://mysites-test/&quot;));
  }

} 
</pre>



<p>Now, we&#8217;ll look at a possible implementation:</p>



<pre class="brush: csharp;">
public class PropertyBagItemRepository
{
  private readonly Logger _logger = Logger.Get();

  public T Find&lt;T&gt;() where T : PropertyBagItem, new()
  {
    var property = new T();
    _logger.TraceToDeveloper(&quot;PropertyBagItemRepository: Finding key: {0}&quot;, property.Key);
    return Security.RunWithElevatedPrivileges(() =&gt;
        {
          if (SPFarm.Local.Properties.ContainsKey(property.Key))
          {
            property.Value = SPFarm.Local.Properties[property.Key].ToString();
            _logger.TraceToDeveloper(&quot;PropertyBagItemRepository: Found key with property {0}&quot;, property.Value);
          }
          _logger.TraceToDeveloper(&quot;PropertyBagItemRepository: Unable to find key: {0}&quot;, property.Key);
        return property;
        });
  }
}
</pre>



<p>That should work and we could then add more tests and an implementation for the <code>Save</code> which might look like &#8211; I prefer chaining so I return @T@:</p>



<pre class="brush: csharp;">
public T Save&lt;T&gt;(T property) where T : PropertyBagItem
{
  _logger.TraceToDeveloper(&quot;PropertyBagValueRepository: Save key: {0}&quot;, key);
  Security.RunWithElevatedPrivileges(() =&gt;
  {
    SPFarm.Local.Properties[key] = property.Value;
    SPFarm.Local.Update();
  });
  return property;
}
</pre>



<p>Finally, let&#8217;s look at our next domain concept the environment. In this case, we want to enumerate all environments. So, we&#8217;ll write our integration test (yes, we should have a unit test for this domain concept first):</p>



<pre class="brush: csharp;">
[Test]
public void CanFindEnvironment()
{
  Assert.That(new PropertyBagItemRepository().Find&lt;Environment&gt;().Code, Is.EqualTo(Environment.EnvironmentCode.DEVINT));
}
</pre>



<p>And now we can see that the implementation is a little more complex than the <code>SiteLocation</code> but that we can encapsulate the details well enough &#8211; actually, there is some dodgy code but the point is to illustrate that we need to keep environment logic, parsing and checking altogether:</p>



<pre class="brush: csharp;">
public class Environment : PropertyBagItem
{
  public enum EnvironmentCode { PROD, PREPROD, TEST, DEV }

  public string Key { get { return &quot;EnvironmentKey&quot; } }
  private EnvironmentCode _code;
  public string Value 
  { 
    get { return Enum.GetName(typeof (EnvironmentCode), _code); }
    set { _code = value; }
  }

  
  public Environment(EnvironmentCode code)
  {
    Code = code;
  }

  public Environment(string code)
  {
    Code = Parse(code);
  }
  
  public Environment() : this(EnvironmentCode.DEV) // new() constraint on Find&lt;T&gt; requires parameterless constructor
  {
  }

  public static EnvironmentCode Parse(string property)
  {
    try
    {
      return (EnvironmentCode)Enum.Parse(typeof(EnvironmentCode), property, true);
    }
    catch (Exception)
    { 
      return EnvironmentCode.DEV;
    }
  }
}
</pre>



<p>It wasn&#8217;t that much work really was it?</p>]]></content:encoded>
			<wfw:commentRss>http://blog.goneopen.com/2011/05/sharepoint-tdd-part-7-repository-pattern-for-propertybag/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Putting your model layer in charge of validation</title>
		<link>http://blog.goneopen.com/2011/02/aspnet-mvc-putting-our-model-layer-in-charge-of-validation/</link>
		<comments>http://blog.goneopen.com/2011/02/aspnet-mvc-putting-our-model-layer-in-charge-of-validation/#comments</comments>
		<pubDate>Sun, 27 Feb 2011 10:40:54 +0000</pubDate>
		<dc:creator>todd</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.goneopen.com/2011/02/aspnet-mvc-putting-our-model-layer-in-charge-of-validation/</guid>
		<description><![CDATA[This title is directly taken for a section in Steve Sanderson&#8217;s book on Asp.Net MVC2 (2nd Edition). I have been struggling with using MVVM with model binding validations built in vs a domain model that binds up to the ModelState. I&#8217;m thinking that there is room for there both but using both approaches may be [...]]]></description>
			<content:encoded><![CDATA[<p>This title is directly taken for a section in <a href="http://www.amazon.com/ASP-NET-Framework-Experts-Voice-NET/dp/1430228865">Steve Sanderson&#8217;s book</a> on Asp.Net <span class="caps">MVC2 </span>(2nd Edition). I have been struggling with using <span class="caps">MVVM </span>with model binding validations built in vs a domain model that binds up to the ModelState. I&#8217;m thinking that there is room for there both but using both approaches may be confusing.</p>

<p>When thinking about validation, he suggests that there are three ways in which the first two are build into <span class="caps">MVC </span>(p.450):</p>


<ul>
<li>Making demands about the presence or format of data that users may enter into a UI</li>
<li>Determining whether a certain .NET object is in a state that you consider valid</li>
<li>Applying business rules to allow or prevent certain operations being carried out against your domain model</li>
</ul>



<p>And I&#8217;m like a lot of people I worry about and begin with the third item first. That&#8217;s why I build out my domain first and then worry about the UI (that&#8217;s not to say that I don&#8217;t build out my domain while thinking about the UI!). </p>

<p>So, model validations in the model binding are really easy. There&#8217;s no wiring needed, they really do just work. For scaffolding, they&#8217;re great. They feel just like my first days on Rails. But to be honest, I suspect that as I craft my views and particularly head towards a fat-client (aka rest-based, jQuery-based client) that all this binding won&#8217;t be needed. But my domain still needs to be rock solid. Something still felt wrong from my experience. Luckily, Sanderson gets to it and the end of the chapter. On p.472 he explains that we need to put the model layer in charge because all this binding is not an ideal separation of concerns and leads to practical problems of repetition, obscurity, restriction of technology choices (phew, can I use Castle?) and my favourite, an &#8220;unnatural chasm between validation rules and business rules&#8221;. He reckons that dropping in a <code>[Required]</code> on a model is convenient for the UI but in practice there are business rules in behind that get more complex.</p>

<p>Of course, the solution isn&#8217;t hard and it was just as I have already done. It requires:</p>


<ul>
<li>a list of errors (which usually involve rule information where (properties) and what (the values) that were a problem)</li>
<li>often wrapping those in an exception</li>
<li>a handler that binds those to the <code>ModelState</code> (because it is the mvc specific part)</li>
</ul>



<p>Thanks Steve. I was wondering how I was going to explain this to the group I am about to teach next week. Here&#8217;s some code that I use (and I think some of this was from a colleague Mark originally).</p>

<p>Here&#8217;s our errors and summary of errors:</p>



<pre class="brush:csharp">
  public struct Error
  {
      public string Key { get; set; }
      public string Message { get; set; }

      public Error(string key, string message) : this()
      {
          Key = key;
          Message = message;
      }
  }
</pre>





<pre class="brush:csharp">
  public class ErrorSummary
  {
      public static ErrorSummary Empty
      {
          get { return new ErrorSummary(new List&lt;Error&gt;()); }
      }

      public List&lt;Error&gt; Errors { get; private set; }

      public ErrorSummary(List&lt;Error&gt; errors)
      {
          Errors = errors;
      }

      public ErrorSummary(Error error) :
          this(new List&lt;Error&gt; {error })
      {
      }
      public ErrorSummary(string key, string message) :
          this( new Error(key, message))
      {
      }

      public ErrorSummary AddError(string key, string message)
      {
          Errors.Add(new Error(key, message));
          return this;
      }
  }
</pre>



<p>Then we&#8217;ll wrap them in an exception to caught in the mvc framework:</p>



<pre class="brush:csharp">
  public class BusinessRuleException : Exception
   {
       public BusinessRuleException(ErrorSummary summary)
       {
           Summary = summary;
       }

       public BusinessRuleException(string key, string message)
       {
           Summary = new ErrorSummary(key, message);
       }

       public BusinessRuleException(string message)
       {
           Summary = new ErrorSummary(&quot;&quot;, message);
       }

       public virtual ErrorSummary Summary { get; private set; }
   }
</pre>



<p>Now we need some code that with gather the errors from our validation framework (eg Castle in this case). We&#8217;ll construct them as extension methods for fluent syntax.</p>



<pre class="brush:csharp">
  /// &lt;summary&gt;
  /// Validation extensions to wrap around PI models using the Castle Validations
  /// &lt;/summary&gt;
  public static class ValidationExtension
  {
      private static readonly CachedValidationRegistry Registry = new CachedValidationRegistry();

      public static bool IsValid&lt;T&gt;(this T model) where T : class 
      {
          return new ValidatorRunner(Registry).IsValid(model);
      }

      public static ErrorSummary GetErrors&lt;T&gt;(this T model) where T : class
      {
          var runner = new ValidatorRunner(Registry);
          return !runner.IsValid(model) ? ToErrorSummary(runner, model) : ErrorSummary.Empty;
      }

      public static void ThrowValidationSummary&lt;T&gt;(this T model) where T : class
      {
          var runner = new ValidatorRunner(Registry);
          if (!runner.IsValid(model))
          {
              throw new BusinessRuleException(ToErrorSummary(runner, model));
          }
      }

      private static ErrorSummary ToErrorSummary&lt;T&gt;(IValidatorRunner runner, T model)
      {
          return new ErrorSummary(ToErrors(runner, model));
      }

      private static List&lt;Error&gt; ToErrors&lt;T&gt;(IValidatorRunner runner, T model)
      {
          var errors = new List&lt;Error&gt;();
          var errorSummary = runner.GetErrorSummary(model);
          for (var i = 0; i &lt; errorSummary.ErrorsCount; i++)
          {
              errors.Add(new Error(errorSummary.InvalidProperties[i], errorSummary.ErrorMessages[i]));
          }
          return errors;
      }
  }
</pre>



<p>Now for <span class="caps">MVC </span>controller code. Here we check that a model is valid and throw summary if it isn&#8217;t valid. We catch the exception and then bind it in the ModelState. </p>



<pre class="brush:csharp">
  public ActionResult SomeAction(Model model)
   {    
        try  // very naive implementation
        {
           model.ThrowValidationSummary();
        }
        catch (Exception ex)
        {
            if (ErrorHandling != null)
                ErrorHandling(ex, ModelState);
            else
                throw;
        }

       // rest of implementation
   }

   protected Action&lt;Exception, ModelStateDictionary&gt; ErrorHandling = (ex, m) =&gt;
   {
       if (typeof(BusinessRuleException) == ex.GetType())
       {
           ((BusinessRuleException)ex).Summary.Errors.ForEach(x =&gt; m.AddModelError(x.Key, x.Message));
       }
       else if (typeof(ArgumentException) == ex.GetType())
       {
           m.AddModelError(((ArgumentException)ex).ParamName, ex.Message);
       }
       else if (typeof(UnauthorizedAccessException) == ex.GetType())
       {
           m.AddModelError(&quot;Authorization&quot;, &quot;Authorisation Denied&quot;);
       }
       else if (typeof(HttpRequestValidationException) == ex.GetType())
       {
           m.AddModelError(&quot;Validation&quot;, &quot;Error&quot;);
       }
   };
</pre>



<p>In practice, this code would be split up. The model checking lives in the service/repository doing the work. I would have the exception handling centralised (eg base class). The list of exception handlers really should be registered a little more nicely than this too. </p>

<p>Go and have a read of Sanderson. You&#8217;ll see a similar implementation. A final point by him. This doesn&#8217;t mean the death of client-side validation.</p>

<blockquote><p>Just because your model layer enforces its own rules doesn&#8217;t mean you have to stop using <span class="caps">ASP.NET MVC&#8217;</span>s built-in validation support. I find it helpful to think of <span class="caps">ASP.NET MVC&#8217;</span>s validation mechanism as a useful first line of defense that is especially good at generating a client-side validation script with virtually no work. It fits in neatly with the view model pattern (i.e., having simple view-specific models that exist only to transfer data between controllers and views and do not hold business logic): each view model class can use Data Annotations attributes to configure client-side validation.<br />
But still, your domain layer shouldn&#8217;t trust your UI layer to enforce business rules. The real enforcement code has to go into the domain using some technique like the one you&#8217;ve just seen. (p.476)</p></blockquote>

<p>So now I&#8217;m heading off to look at knockout.js &#8211; I&#8217;m hoping for the it to help me with client-side validation.</p>]]></content:encoded>
			<wfw:commentRss>http://blog.goneopen.com/2011/02/aspnet-mvc-putting-our-model-layer-in-charge-of-validation/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>UrlBinder for model properties using Url as a type</title>
		<link>http://blog.goneopen.com/2011/02/aspnet-mvc-url-model-binder/</link>
		<comments>http://blog.goneopen.com/2011/02/aspnet-mvc-url-model-binder/#comments</comments>
		<pubDate>Sun, 27 Feb 2011 09:39:34 +0000</pubDate>
		<dc:creator>todd</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[aspnetmvc]]></category>

		<guid isPermaLink="false">http://blog.goneopen.com/2011/02/aspnet-mvc-url-model-binder/</guid>
		<description><![CDATA[I had the simple problem that my Url properties wouldn&#8217;t bind when return back into an action on a controller (in asp.net mvc 2). Take the model below, I want to have a destination as an Url. Seems fair? public class Banner { public string Name { get; set; } public Url Destination { get; [...]]]></description>
			<content:encoded><![CDATA[<p>I had the simple problem that my <code>Url</code> properties wouldn&#8217;t bind when return back into an action on a controller (in asp.net mvc 2). Take the model below, I want to have a destination as an Url. Seems fair?</p>



<pre class="brush:csharp">
  public class Banner
  {
      public string Name { get; set; }
      public Url Destination { get; set; }
  }
</pre>

<p> </p>

<p>Looking at the controller code below, when I enter the action where I had done a form post to I just couldn&#8217;t see a value in the <code>banner.Destination</code> but I could see one in <code>banner.Name</code>. </p>



<pre class="brush:csharp">
  public ActionResult Create(Banner banner)
   {
       // banner had no Destination value but did have Name  
       // ... rest of code
   }
</pre>



<p>Wow, I thought. No <code>Url</code>. HHhhhhmmmm. But I really want to be strongly typed &#8211; all my unit and integration tests worked and I felt that I wanted my domain model to remain, well, <em>true</em>. Given how long it took me to research the solution one suspects I should have just made the <code>Url</code> and <code>string</code>. But I didn&#8217;t and I&#8217;m glad. The solutions <em>is</em> simple and I understand the pipeline much better.</p>

<p>I need to implement <code>IModelBinder</code> for the model <code>Url</code> (which is used by the property). While <code>Url</code> isn&#8217;t a custom class for our domain it is treated as one by mvc. Here is my <code>UrlModelBinder</code> implementation and hooking it up. </p>



<pre class="brush:csharp">
  public class UrlBinder : IModelBinder
  {
      public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
      {
          if (!String.IsNullOrEmpty(bindingContext.ModelName))
          {
              var name = bindingContext.ModelName;
              var rawvalue = bindingContext.ValueProvider.GetValue(name).AttemptedValue;
              var value = new ValueProviderResult(rawvalue, rawvalue, CultureInfo.CurrentCulture);
              bindingContext.ModelState.SetModelValue(name, value);
              return new Url(rawvalue);  // I'm unclear that this needs to be returned
          }
          return null;
      }
  }
</pre>



<p>And then ensuring that it resolves against the <code>Url</code>.</p>



<pre class="brush:csharp">
  protected override void  Application_Start()
  { 
      ModelBinders.Binders.Add(typeof(Url), new UrlBinder());
  }
</pre>



<p>So, the key to this solution is understanding &#8211; and this is quite obvious now that I understand the implementation in <code>DefaultModelBinder</code> &#8211; is that <code>Url</code> is a <strong>model</strong> and not a <strong>property</strong>. I kept thinking that I needed bind the form value to the property. Well I do but for a &#8220;custom&#8221; type. <code>Url</code> is custom because (as the documentation clearly states) it is does not inherit from string. Only string properties are bind by default &#8211; that includes enumerations of string (eg <code>IList</code>). So once you know that, it is straightforward that the solution is to implement your own <code>IModelBinder</code> for <code>Url</code>. (If you are interested use Reflector or the source on CodePlex and look through the <code>DefaultModelBinder</code> &#8211; you&#8217;ll see the way they implement <code>BindSimpleModel</code> and <code>BindComplexModel</code>)</p>

<p>This binder is pretty naive so I expect as I learn more it will be improved. Something I didn&#8217;t expect was that I don&#8217;t really need to construct an <code>Url</code> because in the model binding at this stage I just need be able to have a binder for the type rather than worry about constructing the type. I do this by putting <code>rawvalue</code> into the <code>ValueProviderResult</code> &#8211; it only accepts strings. This code then gets picked up again in the <code>DefaultModelBinder</code> when it constructs the model (in this case <code>Banner</code>) which it then easily creates a <code>new Url(value)</code>.</p>

<p>A simple question, why isn&#8217;t there a binder for <code>Url</code> already in the code? Is not <code>Url</code> effectively primitive for the web? <em>Clearly</em> not.</p>

<p>If you&#8217;ve got this far and are interested there are other ways that you really don&#8217;t want to use to solve this problem:</p>


<ul>
<li>use an action filter (<code>[Bind(exclude=&quot;Destination&quot;)]</code>) and then read it from the <code>Request.Form</code></li>
<li>implement my own <code>IValueProvider</code> on the property <code>banner</code></li>
<li>rewrite the <code>ModelState</code> explicitly clearing errors first</li>
<li>implement an <code>IModelBinder</code> for the <code>Banner</code> class</li>
<li>and the biggest and most heavy-handed of all, subclass <code>DefaultModelBinder</code></li>
</ul>



<p>Luckily, none of these solutions are needed. None will feel right because they are either too specific to the class or property, too kludgy because they use <code>Request.Form</code> and just way too big for a small problem.</p>]]></content:encoded>
			<wfw:commentRss>http://blog.goneopen.com/2011/02/aspnet-mvc-url-model-binder/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Software Craftsmanship and TDD</title>
		<link>http://blog.goneopen.com/2011/01/software-craftsmanship-and-tdd/</link>
		<comments>http://blog.goneopen.com/2011/01/software-craftsmanship-and-tdd/#comments</comments>
		<pubDate>Mon, 17 Jan 2011 03:36:35 +0000</pubDate>
		<dc:creator>todd</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.goneopen.com/2011/01/software-craftsmanship-and-tdd/</guid>
		<description><![CDATA[I gave a talk on software craftmanship back about a year ago. At that time, I spoke to handful of slides and woefully overtime. Since then I extended the slides to just under 40 that may or may not be readable. But I thought that it might be time to put these up if anyone [...]]]></description>
			<content:encoded><![CDATA[<p>I gave a talk on software craftmanship back about a year ago. At that time, I spoke to handful of slides and woefully overtime. Since then I extended the slides to just under 40 that may or may not be readable. But I thought that it might be time to put these up if anyone is interested.</p>

<p>Below is the abstract for the <a href="http://bit.ly/eCHvXs">slides as a pdf</a></p>

<blockquote><p>Software craftsmanship is a movement about getting better at software development particularly through better coding skills. This talk will look at some key discussions over the last ten years with a particular focus on Sennett&#8217;s ideas from The Craftsman and ask: what does it mean to become a craftsman or craftswoman? how do we get better? I also look at why as craftspeople we might be troubled and when we may need to be vigilant! I will try outline how this is relevant to practices like continuous integration and test-driven development.</p></blockquote>]]></content:encoded>
			<wfw:commentRss>http://blog.goneopen.com/2011/01/software-craftsmanship-and-tdd/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
