<?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>invalid cast</title>
	<atom:link href="http://invalidcast.com/feed" rel="self" type="application/rss+xml" />
	<link>http://invalidcast.com</link>
	<description>(sense)nonsense;</description>
	<lastBuildDate>Tue, 15 Nov 2011 09:10:37 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>The Ordered Jobs Kata</title>
		<link>http://invalidcast.com/2011/09/the-ordered-jobs-kata/</link>
		<comments>http://invalidcast.com/2011/09/the-ordered-jobs-kata/#comments</comments>
		<pubDate>Mon, 26 Sep 2011 12:17:20 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://invalidcast.com/?p=513</guid>
		<description><![CDATA[As you may well know, a kata is a training exercise that is performed over and over to build muscle memory and generally improve at whatever it is that we’re practising. The term kata comes from martial arts, but us software guys/gals have started using the term to describe the solving of small problems repeatedly [...]]]></description>
			<content:encoded><![CDATA[<p align="justify"><img style="background-image: none; border-right-width: 0px; margin: 0px 0px 0px 15px; padding-left: 0px; padding-right: 0px; display: inline; float: right; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Kata" border="0" alt="Kata" align="right" src="http://invalidcast.com/wp-content/uploads/2011/09/Kata.jpg" width="88" height="112" />As you may well know, a kata is a training exercise that is performed over and over to build muscle memory and generally improve at whatever it is that we’re practising. The term kata comes from martial arts, but us software guys/gals have started using the term to describe the solving of small problems repeatedly to get better at things like TDD and pairing.</p>
<p align="justify">Katas also have the added benefit of making non-geeks think we’re healthy individuals that don’t just sit in dark basements all day. In fact, we’ve started using the word dojo to make absolutely sure our new image sticks.</p>
<p>  <span id="more-513"></span>
<p align="justify">Anyway, I had an interesting kata-like problem at work and I figured it’d be cool to describe it here for the masses of programmers out there having cold sweats and shaking in need of their next kata fix.</p>
<p align="justify">
<p align="justify">Feel free to have a go, and if you do, please leave a comment linking to your solution so I can collect them all at the bottom of this post. Then we can all mock each other (no pun intended). It’ll also be interesting to see if the choice of programming language affects the solution.</p>
<p align="justify"><strong>The Kata</strong></p>
<p align="justify">Imagine we have a list of jobs, each represented by a character. Because certain jobs must be done before others, a job may have a dependency on another job. For example, <strong>a</strong> may depend on <strong>b</strong>, meaning the final sequence of jobs should place <strong>b</strong> before <strong>a</strong>. If <strong>a</strong> has no dependency, the position of <strong>a</strong> in the final sequence does not matter.</p>
<p align="justify">The goal of the kata is to parse the job dependency structure and produce a sequence of jobs in the order that observes their dependency chain.</p>
<p align="justify">Start with a method that accepts a single <em>string</em> argument and returns a <em>string</em> which represents the ordered sequence of jobs (since each job is a single character). We’ll refine the algorithm by evolving the requirements with each step, just like the <a href="http://osherove.com/tdd-kata-1/" target="_blank">string calculator kata</a>.</p>
<p align="justify"><strong>Step 1 – Empty String</strong></p>
<p align="justify">Given you’re passed an empty string (no jobs), the result should be an empty sequence.</p>
<p align="justify"><strong>Step 2 – Single Job</strong></p>
<p align="justify">Given the following job structure:</p>
<pre class="brush: plain;">a =&gt;</pre>
<p align="justify">The result should be a sequence consisting of a single job <strong>a</strong>.</p>
<p align="justify"><strong>Step 3 – Multiple Jobs</strong></p>
<p align="justify">Given the following job structure:</p>
<pre class="brush: plain;">a =&gt;
b =&gt;
c =&gt;</pre>
<p align="justify">The result should be a sequence containing all three jobs <strong>abc</strong> in no significant order.</p>
<p align="justify"><strong>Step 4 – Multiple Jobs, Single Dependency</strong></p>
<p align="justify">Given the following job structure:</p>
<pre class="brush: plain;">a =&gt;
b =&gt; c
c =&gt;</pre>
<p align="justify">The result should be a sequence that positions <strong>c</strong> before <strong>b</strong>, containing all three jobs <strong>abc</strong>.</p>
<p align="justify"><strong>Step 5 – Multiple Jobs, Multiple Dependencies</strong></p>
<p align="justify">Given the following job structure:</p>
<pre class="brush: plain;">a =&gt;
b =&gt; c
c =&gt; f
d =&gt; a
e =&gt; b
f =&gt;</pre>
<p align="justify">The result should be a sequence that positions <strong>f</strong> before <strong>c</strong>, <strong>c</strong> before <strong>b</strong>, <strong>b</strong> before <strong>e</strong> and <strong>a </strong>before <strong>d </strong>containing all six jobs <strong>abcdef</strong>.</p>
<p align="justify"><strong>Step 6 – Multiple Jobs, Self Referencing Dependency</strong></p>
<p align="justify">Given the following job structure:</p>
<pre class="brush: plain;">a =&gt;
b =&gt;
c =&gt; c</pre>
<p align="justify">The result should be an error stating that jobs can’t depend on themselves.</p>
<p align="justify"><strong>Step 7 – Multiple Jobs, Circular Dependency Chain</strong></p>
<p align="justify">Given the following job structure:</p>
<pre class="brush: plain;">a =&gt;
b =&gt; c
c =&gt; f
d =&gt; a
e =&gt;
f =&gt; b</pre>
<p align="justify">The result should be an error stating that jobs can’t have circular dependencies.</p>
<p align="justify"><strong>Completed Solutions</strong></p>
<p align="justify"><strong>In Ruby</strong></p>
<p><a href="http://twitter.com/wisemonkeyash" target="_blank">Ash</a> <a href="https://github.com/ashmoran/ordered_jobs_kata" target="_blank">solves the kata</a> using <a href="http://rubygems.org/gems/rgl" target="_blank">RGL</a> and <a href="http://rspec.info/" target="_blank">RSpec</a></p>
<p><a href="http://twitter.com/caius" target="_blank">Caius</a> <a href="https://github.com/caius/OrderedJobs" target="_blank">solves the kata</a> using black magic and <a href="https://github.com/peterc/testrocket" target="_blank">testrocket</a></p>
<p><a href="http://twitter.com/samsworldofno" target="_blank">Sam</a> <a href="https://github.com/samdanavia/ordered-jobs-kata" target="_blank">solves the kata</a> using <a href="http://rspec.info/" target="_blank">RSpec</a></p>
<p><a href="http://twitter.com/kevinrutherford" target="_blank">Kevin</a> <a href="https://github.com/kevinrutherford/ordered-jobs" target="_blank">solves the kata</a> in the style of <a href="http://www.spaconference.org/spa2010/sessions/session255.html" target="_blank">TDD as if you meant it</a> using <a href="http://rspec.info/" target="_blank">RSpec</a></p>
<p><a href="http://twitter.com/eightbitraptor" target="_blank">Matt</a> <a href="https://gist.github.com/1365150" target="_blank">solves the kata</a> using <a href="http://rspec.info/" target="_blank">RSpec</a></p>
<p><strong>In C++</strong></p>
<p><a href="http://twitter.com/drummertom999" target="_blank">Thomas</a> <a href="https://bitbucket.org/drummertom999/ordered-jobs-kata/overview" target="_blank">solves the kata</a> using <a href="http://en.wikipedia.org/wiki/C%2B%2B11" target="_blank">C++11</a></p>
<p><strong>In C#</strong></p>
<p><a href="http://twitter.com/martinrue" target="_blank">Martin</a> <a href="https://github.com/martinrue/ordered-jobs-kata" target="_blank">solves the kata</a> using <a href="https://github.com/machine/machine.specifications" target="_blank">MSpec</a></p>
<p><a href="http://twitter.com/thomaseyde" target="_blank">Thomas</a> <a href="https://bitbucket.org/thomaseyde/the-ordered-jobs-kata" target="_blank">solves the kata</a> using <a href="http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.aspx" target="_blank">MSTest</a></p>
<p><a href="http://twitter.com/ruby_gem" target="_blank">Gemma</a> <a href="https://github.com/rubygem/OrderedJobsKata" target="_blank">solves the kata</a> using <a href="http://www.nunit.org/" target="_blank">NUnit</a></p>
<p><strong>In Python</strong></p>
<p><a href="https://twitter.com/Frimkron" target="_blank">Mark</a> <a href="http://pastebin.com/qgXLjdBY" target="_blank">solves the kata</a> using <a href="http://docs.python.org/library/unittest.html" target="_blank">unittest</a></p>
<p><strong>In SQL (yes, SQL)</strong></p>
<p><a href="https://twitter.com/sherwinrice" target="_blank">Sherwin</a> <a href="http://codepaste.net/4frztp" target="_blank">solves the kata</a> using manual tests</p>
<p><a href="http://twitter.com/johnnonolan" target="_blank">Johnno</a> <a href="https://github.com/johnnonolan/orderedjobs" target="_blank">solves the kata</a> using <a href="https://github.com/johnnonolan/orderedjobs/blob/master/TestScript.sql" target="_blank">EYEUnit</a></p>
<p><a href="http://twitter.com/kevriley" target="_blank">Kev</a> <a href="http://dl.dropbox.com/u/32682384/OrderedJobs.sql" target="_blank">solves the kata</a> using manual tests</p>
<p><strong>In CoffeeScript</strong></p>
<p><a href="http://twitter.com/thetombell" target="_blank">Tom</a> <a href="https://github.com/tombell/ordered-jobs" target="_blank">solves the kata</a> using <a href="https://github.com/caolan/nodeunit" target="_blank">nodeunit</a> and <a href="http://tombell.org.uk/ordered-jobs/" target="_blank">documents</a> his solution</p>
<p><strong>In Scala</strong></p>
<p><a href="http://twitter.com/workmad3" target="_blank">David</a> <a href="https://github.com/workmad3/ordered-jobs-scala" target="_blank">solves the kata</a> using <a href="http://code.google.com/p/specs/" target="_blank">specs</a></p>
<p><strong>In JavaScript</strong></p>
<p><a href="http://twitter.com/samsworldofno" target="_blank">Sam</a> <a href="https://github.com/samdanavia/ordered-jobs-kata" target="_blank">solves the kata again</a> using <a href="http://pivotal.github.com/jasmine/" target="_blank">Jasmine</a></p>
]]></content:encoded>
			<wfw:commentRss>http://invalidcast.com/2011/09/the-ordered-jobs-kata/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>C# News From The Future: What If?</title>
		<link>http://invalidcast.com/2011/07/c-news-from-the-future-what-if/</link>
		<comments>http://invalidcast.com/2011/07/c-news-from-the-future-what-if/#comments</comments>
		<pubDate>Thu, 14 Jul 2011 14:54:38 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://invalidcast.com/?p=499</guid>
		<description><![CDATA[It’s a fresh September morning and I can’t quite believe it’s actually available – we’ve got a preview release of C# 6. Ever since the announcement at PDC2012 last month, I’ve been waiting to play around with a particular new feature. I remember it being a fairly average PDC until Anders shocked everyone with it [...]]]></description>
			<content:encoded><![CDATA[<p align="justify">It’s a fresh September morning and I can’t quite believe it’s actually available – we’ve got a preview release of C# 6. Ever since the announcement at PDC2012 last month, I’ve been waiting to play around with a particular new feature. I remember it being a fairly average PDC until Anders shocked everyone with it – method group assignment.</p>
<p align="justify">Initially, I wondered what exactly it meant until someone on Twitter clarified it.</p>
<p><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2011/07/Untitled.png" width="347" height="120" /></p>
<p>  <span id="more-499"></span>
<p align="justify">Monkey patching! It surprised me because, until now, I saw the future of C# as an increasing story of ceremony. In recent months F# has been gaining an unbelievable amount of attention because of its awesome inference and perceived simplicity due to lack of ceremony. And let’s not even mention Ruby.</p>
<p align="justify">Lots of the dynamic languages, in fact, seem to involve much less work these days when it comes to bending the language into a shape that fits the problem well. And really, that’s what we do as programmers. The question is: how can the language be so flexible that it lets us solve any problem?</p>
<p align="justify"><strong>Without Monkey Patching</strong></p>
<p align="justify">I’ve been writing a really simple app that lets users register for an account and store notes. Until today, I had been jumping through hoops trying to aim for the right amount of SRP and DI that makes this thing testable. What I ended up doing was extracting an interface for each dependency of the unit that I needed to test, so that I could test it in complete isolation.</p>
<p align="justify">We know that interfaces weren’t intended solely for producing seams for testing, but that’s pretty much how we all use them anyway. We end up with two, three, maybe four additional interfaces and associated classes, and a dependency chain, when all we really wanted was to test the damn thing.</p>
<p align="justify">It’s true that we potentially get a better design in terms of looser coupling and separation of concerns, but get this: I don’t want that in this case. This is a single controller app with a small and perfectly understandable behaviour. I should be able to bend C# (and not have to work around it) into testing my app.</p>
<p align="justify">Ultimately we end up trading complexity for testability. Incidentally, isn’t complexity proportional to number of bugs? In reality, testability should be easy and should be part of <a href="http://blogs.msdn.com/b/brada/archive/2003/10/02/50420.aspx" target="_blank">the pit of success</a>.</p>
<p align="justify"><strong>C# Just Took Up Yoga</strong></p>
<p align="justify">Well, things just changed. From what I understand, the CLR guys managed to implement new functionality that allows the assignment of a delegate to a method group. It does some kind of smart matching with the delegate parameters. I don’t know all the technical details, but I do know that it freaking rocks.</p>
<p>Consider my simple app:</p>
<pre class="brush: csharp;">public class UserService
{
    public void Register(string username)
    {
        using (var context = new DataContext())
        {
            context.Users.Add(new User
            {
                Username = username,
                Created = DateTime.Now
            });

            context.SaveChanges();
        }

        Notifications.Send(&quot;New user: &quot; + username);
    }
}</pre>
<p align="justify">Normally I’d be coupled to <em>DataContext</em>, <em>DateTime.Now </em>and my static <em>Notifications.Send</em> method, making unit testing this method particularly difficult. But since C# 6 supports monkey patching, this thing is now perfectly testable and without the otherwise unnecessary interfaces and complexity. </p>
<p align="justify">We can patch <em>DataContext</em> (stubbing it, in test parlance) and make it do nothing. We can patch <em>DateTime.Now</em> to give us a more predictable value. And we can certainly patch <em>Notifications.Send</em> so that it doesn’t send anything and just allows us to inspect the message.</p>
<p align="justify">Here’s the test:</p>
<pre class="brush: csharp;">[Test]
public void Register_WithValidUsername_RegisterUserAndNotifies()
{
    User user;
    string notification;

    // Patch

    DateTime.Now = () =&gt; new DateTime(1, 1, 1);

    DataContext.SaveChanges = (context) =&gt;
    {
        user = context.Users.FirstOrDefault();
    };

    Notifications.Send = (msg) =&gt;
    {
        notification = msg;
    };

    // Act

    new UserService.Register(&quot;bob&quot;);

    // Asset

    Assert.That(user.Username, Is.EqualTo(&quot;bob&quot;));
    Assert.That(user.Created.Year, Is.EqualTo(1));
    Assert.That(user.Created.Month, Is.EqualTo(1));
    Assert.That(user.Created.Day, Is.EqualTo(1));
    Assert.That(notification, Is.EqualTo(&quot;New user: bob&quot;));
}</pre>
<p><strong></strong></p>
<p><strong>Not Limited To Testing</strong></p>
<p align="justify">Monkey patching (also know as duck punching, if you prefer) is not only useful for testing. This new ability to patch stuff means we can replace behaviour in classes that we don’t necessarily own.</p>
<p align="justify">Some HTTP library you’re using have a broken URL encoding method? Just patch it. Want to redirect a method to somewhere else without introducing a subclass? Just patch it.</p>
<p><strong>What Does This Mean?</strong></p>
<p align="justify">Today was a big day for C# – it just became easier to fall into the pit of success:</p>
<ul>
<li>
<div align="justify">Testing code is now much easier out of the box since all we have to do is stub it via a good old duck punch to the gut. </div>
</li>
<li>
<div align="justify">We don’t have to introduce 5 interfaces purely for the sake of testability when the design doesn’t require such decoupling. </div>
</li>
<li>
<div align="justify">All that legacy (otherwise untestable) code is now testable – just patch it. </div>
</li>
<li>
<div align="justify">Bugs in code we don’t own just became fixable. </div>
</li>
</ul>
<p align="justify">But most importantly, C# gave us back some control and <a href="http://tekpub.com/conferences/rubyconf2010/dhh" target="_blank">let us decide what’s dangerous and what’s not</a>. C# just became more flexible and gave us a chance to be more awesome with it. C# just trusted us.</p>
]]></content:encoded>
			<wfw:commentRss>http://invalidcast.com/2011/07/c-news-from-the-future-what-if/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Tinyweb Series: 5 To-do Demo</title>
		<link>http://invalidcast.com/2011/05/tinyweb-series-5-to-do-demo/</link>
		<comments>http://invalidcast.com/2011/05/tinyweb-series-5-to-do-demo/#comments</comments>
		<pubDate>Wed, 18 May 2011 16:09:57 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Projects]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://invalidcast.com/?p=481</guid>
		<description><![CDATA[In the previous post in this series we saw how to render Spark views from handlers, looking at the use of view models and master page layouts. Finally, we took a more in-depth look at model binding support in Tinyweb. In the final post, we’ll work through a to-do list demo which will pull together [...]]]></description>
			<content:encoded><![CDATA[<p align="justify">In the <a href="http://invalidcast.com/2011/05/tinyweb-series-4-views-model-binding/" target="_blank">previous post</a> in this series we saw how to render Spark views from handlers, looking at the use of view models and master page layouts. Finally, we took a more in-depth look at model binding support in Tinyweb.</p>
<p align="justify">In the final post, we’ll work through a to-do list demo which will pull together a number of the features already covered in the series into a complete application.</p>
<p>    <span id="more-481"></span>
<p align="justify"><strong>What We’re Building</strong></p>
<p align="justify">We’re going to build a simple web application with a JSON/XML API that allows the creation, deletion and completion of simple to-do items. We’ll have a view that displays the current list, a method for removing and completing individual items and a form for creating new ones.</p>
<p align="justify"><strong>The Resources</strong></p>
<p align="justify">Let’s consider which resources we’ll need to create in order to support the requirements.</p>
<p align="justify"><strong>/login</strong></p>
<p align="justify">The <em>LoginHandler</em> will allow a user to authenticate by providing a login view.</p>
<p align="justify"><strong>/todo/list</strong></p>
<p align="justify">The <em>TodoListHandler</em> will display the current list of to-do items.</p>
<p align="justify"><strong>/todo/add</strong></p>
<p align="justify">The <em>TodoAddHandler</em> will create a new item and redirect back to the list.</p>
<p align="justify"><strong>/todo/complete</strong></p>
<p align="justify">The <em>TodoCompleteHandler</em> will complete an item and redirect back to the list.</p>
<p align="justify"><strong>/todo/uncomplete</strong></p>
<p align="justify">The <em>TodoUncompleteHandler</em> will undo the completed status and redirect back to the list.</p>
<p align="justify"><strong>/todo/remove</strong></p>
<p align="justify">The <em>TodoRemoveHandler</em> will delete an item and redirect back to the list.</p>
<p align="justify"><strong>The API</strong></p>
<p align="justify">As it’s a demo, we’ll keep the API simple. Our imaginary requirement here is that the current to-do list should be available outside of the application for things like external widgets or mobile phone applications to consume.</p>
<p align="justify">We’ll achieve this with a single handler at <strong>/api/todo/list </strong>that returns the current to-do list in either JSON or XML format.</p>
<p align="justify"><strong>Authentication</strong></p>
<p align="justify">For the sake of keeping the demo easy to understand, our security requirements are simply going to be that a user must log in using a hard-coded username and password before they can use the application. We’ll use an authentication filter to implement this.</p>
<p align="justify"><strong>Logging</strong></p>
<p align="justify">Finally, to catch any errors with our to-do list, we’ll also implement error logging so that we can periodically check any exceptions that have been thrown by the handlers.</p>
<p align="justify"><strong>Here’s One I Prepared Earlier</strong></p>
<p align="justify">To use the demo, the first thing we need to do is authenticate at <strong>/login </strong>using the hard-coded username and password <em>admin</em> and <em>password</em> respectively:</p>
<p align="justify"><strong><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2011/05/1.png" width="509" height="238" /></strong></p>
<p align="justify">We’re then presented with the to-do list at <strong>/todo/list</strong>:</p>
<p align="justify"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2011/05/2.png" width="512" height="324" /></p>
<p align="justify">Now that we have a feel for what this thing looks like, let’s go through the implementation details and discuss how it’s built with Tinyweb. If you’d like to follow along beyond the snippets used in the rest of this post, you can do so by looking at the <a href="https://github.com/martinrue/Todo-Demo" target="_blank">demo code on github</a>.</p>
<p align="justify"><strong>Project Layout</strong></p>
<p align="justify">Although Tinyweb does not enforce a particular convention in terms of where you put files within the project, I tend to follow my own to be consistent between projects. Handlers go in a Handlers folder, filters in Filters and so on. Here’s the project layout for the to-do demo app.</p>
<p align="justify"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2011/05/3.png" width="243" height="482" /></p>
<p align="justify">It should be fairly easy to figure out what’s going on. Don’t worry too much about the files inside the <a href="https://github.com/martinrue/Todo-Demo/tree/master/src/Todo/Database" target="_blank">Database</a> directory since data access isn’t especially relevant to the demo app. Similarly, the <a href="https://github.com/martinrue/Todo-Demo/tree/master/src/Todo/Content" target="_blank">Content</a> directory isn’t too interesting either, it just contains CSS and JavaScript.</p>
<p align="justify">The core of the app is contained within the directories you see expanded. We have the aforementioned handlers right there in <a href="https://github.com/martinrue/Todo-Demo/tree/master/src/Todo/Handlers" target="_blank">Handlers</a>. Note how I’ve separated the API and the web app handlers to make it more explicit (again, just my own convention here).</p>
<p align="justify">There aren’t many views, so I’ve just bunched them together under <a href="https://github.com/martinrue/Todo-Demo/tree/master/src/Todo/Views" target="_blank">Views</a>. We also have a partial view named Add.spark which just creates a &lt;form&gt; that enables new to-do items to be posted to <strong>/todo/add</strong>.</p>
<p align="justify"><strong>From The Beginning</strong></p>
<p align="justify">As we’ve covered in the previous posts, the first step in creating a Tinyweb app is to initialise the framework in Global.asax:</p>
<pre class="brush: csharp;">protected void Application_Start(object sender, EventArgs e)
{
    Tinyweb.AllowFormatExtensions = true;

    Tinyweb.Init(new DatabaseRegistry());

    Tinyweb.OnError = (exception, request, handler) =&gt;
    {
        var error = String.Format(&quot;Error at {0} from {1}:\r\n{2}&quot;,
                                  handler.Uri,
                                  handler.Type.Name,
                                  exception.ToString());

        var log = request.HttpContext.Server.MapPath(&quot;/errors.txt&quot;);
        File.AppendAllLines(log, new[] { error });
    };
}</pre>
<p align="justify">The first thing we do is turn on format extensions, allowing the Accept header to be specified on the URL (i.e. <strong>/api/todo/list.xml</strong> and <strong>/api/todo/list.json</strong>).</p>
<p align="justify">Next we initialise the framework and pass in a StructureMap registry. The <a href="https://github.com/martinrue/Todo-Demo/blob/master/src/Todo/Global.asax.cs" target="_blank">DatabaseRegistry</a> configures how the <a href="https://github.com/martinrue/Todo-Demo/blob/master/src/Todo/Database/IDatabase.cs" target="_blank">IDatabase</a> dependency (used by handlers to persist the to-do list to a text file database) can be <a href="https://github.com/martinrue/Todo-Demo/blob/master/src/Todo/Database/Database.cs" target="_blank">resolved</a> at runtime.</p>
<p align="justify">Finally, we set up error logging using the Tinyweb.OnError delegate. In this instance, we just want to append to a log file every time an error occurs, storing the handler, the URL and the exception.</p>
<p align="justify">OK – Initialisation – check, let’s look at the root request handler.</p>
<p align="justify"><strong>RootHandler</strong></p>
<p align="justify">I hope you didn’t get too excited, as the <a href="https://github.com/martinrue/Todo-Demo/blob/master/src/Todo/Handlers/Web/RootHandler.cs" target="_blank">RootHandler</a> is pretty dull. The only reason we have a RootHandler is so people new to Tinyweb running the demo actually reach the login page without having to find and enter the URL themselves. As such, RootHandler simply redirects to the LoginHandler:</p>
<pre class="brush: csharp;">public class RootHandler
{
    public IResult Get()
    {
        return Result.Redirect&lt;LoginHandler&gt;();
    }
}</pre>
<p><strong>LoginHandler</strong></p>
<p>Moving right along, the next leg of the request takes us to the <a href="https://github.com/martinrue/Todo-Demo/blob/master/src/Todo/Handlers/Web/LoginHandler.cs" target="_blank">LoginHandler</a>:</p>
<pre class="brush: csharp;">public class LoginHandler
{
    public IResult Get()
    {
        return View.Spark(&quot;Views/Login.spark&quot;, &quot;Master.spark&quot;);
    }

    public IResult Post(RequestContext request, string username,
                                                string password)
    {
        if (username == &quot;admin&quot; &amp;&amp; password == &quot;password&quot;)
        {
            issueCookie(username);
            return Result.Redirect&lt;TodoListHandler&gt;();
        }

        return Result.Redirect&lt;LoginHandler&gt;();
    }

    private void issueCookie(string username)
    {
        var ticket = new FormsAuthenticationTicket(username, true, 60);

        HttpContext.Current.Response.Cookies.Add(
          new HttpCookie(FormsAuthentication.FormsCookieName,
                         FormsAuthentication.Encrypt(ticket))
        );
    }
}</pre>
<p align="justify">When a GET request is made to the LoginHandler, the <a href="https://github.com/martinrue/Todo-Demo/blob/master/src/Todo/Views/Login.spark" target="_blank">login view</a> that we saw in the screenshot is rendered. When the login form is posted back, the username and password are checked against our hard-coded values. If they don’t match, we redirect to the LoginHandler so the user can try again.</p>
<p align="justify">If the username and password are correct, we use ASP.NET Forms Authentication to issue a ticket and log the user in. We can then redirect the user to the to-do list, safe in the knowledge that the authentication filter will let them through.</p>
<p><strong>AuthenticationFilter</strong></p>
<p align="justify">Our <a href="https://github.com/martinrue/Todo-Demo/blob/master/src/Todo/Filters/AuthenticationFilter.cs" target="_blank">AuthenticationFilter</a> runs before every request and makes sure that only authenticated users can access the to-do list.</p>
<pre class="brush: csharp;">public class AuthenticationFilter
{
    IList&lt;Type&gt; allowedHandlers = new List&lt;Type&gt;
    {
        typeof(LoginHandler), typeof(ApiTodoListHandler)
    };

    public IResult Before(RequestContext context,
                          HandlerData handler)
    {
        if (!context.HttpContext.User.Identity.IsAuthenticated)
        {
            if (!allowedHandlers.Contains(handler.Type))
            {
                return Result.Redirect&lt;LoginHandler&gt;();
            }
        }

        return Result.None();
    }
}</pre>
<p align="justify">This is achieved by maintaining a list of <em>allowedHandlers</em> and checking each request against the list. If the request handler is not in the list, a check if made to see if the user has authenticated to determine if they’re allowed access to the resource. If the user isn’t authenticated, a redirect result is returned which bypasses the rest of the execution pipeline and asks the user to log in.</p>
<p align="justify"><strong>TodoListHandler</strong></p>
<p align="justify">When authenticated, we hit the <a href="https://github.com/martinrue/Todo-Demo/blob/master/src/Todo/Handlers/Web/TodoListHandler.cs" target="_blank">TodoListHandler</a>:</p>
<pre class="brush: csharp;">public class TodoListHandler
{
    IDatabase _database;

    public TodoListHandler(IDatabase database)
    {
        _database = database;
    }

    public IResult Get()
    {
        var model = _database.GetAll();

        return View.Spark(model, &quot;Views/List.spark&quot;, &quot;Master.spark&quot;);
    }
}</pre>
<p align="justify">The TodoListHandler is a fairly standard handler which uses its <a href="https://github.com/martinrue/Todo-Demo/blob/master/src/Todo/Database/IDatabase.cs" target="_blank">IDatabase</a> dependency to retrieve the current to-do list.</p>
<p align="justify">The DatabaseRegistry that was registered during initialisation will allow Tinyweb to supply a concrete <a href="https://github.com/martinrue/Todo-Demo/blob/master/src/Todo/Database/Database.cs" target="_blank">Database</a> at runtime. The IDatabase dependency is a file-based database for storing and retrieving the to-do items. In a real application, we might depend on some service class instead of directly depending on a data access class like this, but it’s a demo – it’s allowed to suck.</p>
<p align="justify">The TodoListHandler retrieves the current to-do list and renders the <a href="https://github.com/martinrue/Todo-Demo/blob/master/src/Todo/Views/List.spark" target="_blank">Views/List.spark</a> view, passing the to-do list as the model. Let’s take a look at the view:</p>
<pre class="brush: xml; wrap-lines: false;">&lt;viewdata model=&quot;TodoList&quot; /&gt;

&lt;content name=&quot;header&quot;&gt;

    Todo List

&lt;/content&gt;

&lt;content name=&quot;body&quot;&gt;

    &lt;div if=&quot;!Model.Items.Any()&quot; class=&quot;notification&quot;&gt;
        Woohoo - nothing to do!
    &lt;/div&gt;

    &lt;div each=&quot;var todo in Model.Items&quot; class=&quot;${todo.Complete ? 'complete' : 'todo'}&quot;&gt;

        &lt;div class=&quot;text&quot;&gt;
            ${todo.Text}
        &lt;/div&gt;

        &lt;div class=&quot;date&quot;&gt;
            ${todo.Date.ToString(&quot;dddd dd MMM yy&quot;)}
        &lt;/div&gt;

        &lt;div class=&quot;menu&quot;&gt;
            &lt;a href=&quot;${Url.For&lt;TodoRemoveHandler&gt;(new { todo.ID })}&quot;&gt;Remove&lt;/a&gt; |
            &lt;a href=&quot;${Url.For&lt;TodoUncompleteHandler&gt;(new { todo.ID })}&quot; if=&quot;todo.Complete&quot;&gt;Undo&lt;/a&gt;
            &lt;a href=&quot;${Url.For&lt;TodoCompleteHandler&gt;(new { todo.ID })}&quot; if=&quot;!todo.Complete&quot;&gt;Complete&lt;/a&gt;
        &lt;/div&gt;

        &lt;div class=&quot;clear&quot;&gt;&lt;/div&gt;

    &lt;/div&gt;

    &lt;render partial=&quot;partials/add&quot; /&gt;

&lt;/content&gt;</pre>
<p align="justify">The first thing to note is line 1 where the expected view model type is declared. The view is then broken into two sections – the header and the body.</p>
<p align="justify">The first thing the view does is conditionally show the <em>Woohoo – nothing to do</em> message depending on whether the model contains any to-do items. Notice the very clean <em>if=”” </em>Spark syntax for performing this check.</p>
<p align="justify">Next, the view repeats a &lt;div&gt; for each of the to-do items that exist within the model. For each item, the class of the &lt;div&gt; is set depending on the state of the to-do item (complete or not) and the content of the &lt;div&gt; is built up to reflect the data about the particular item, such as the text and date.</p>
<p align="justify">Lastly, we render the <a href="https://github.com/martinrue/Todo-Demo/blob/master/src/Todo/Views/Partials/Add.spark" target="_blank">Partials/Add.spark</a> view which provides the &lt;form&gt; for creating new to-do items:</p>
<pre class="brush: xml;">&lt;form id=&quot;add&quot; method=&quot;post&quot; action=&quot;${Url.For&lt;TodoAddHandler&gt;()}&quot;&gt;

    &lt;input type=&quot;text&quot; name=&quot;todo&quot; /&gt;

&lt;/form&gt;

&lt;script type=&quot;text/coffeescript&quot;&gt;

    $ -&gt;
      $('#add input').focus()
      $('#add').submit -&gt;
        false if $('#add input').val() is &quot;&quot;

&lt;/script&gt;</pre>
<p align="justify">The partial exists mainly as a demonstration of how this is done using Spark, but also to show how the application might be broken up at the view level to reuse separate elements of the system (we may want to add a to-do item in some other area of the application).</p>
<p align="justify">Also notice the use of the Url.For helper. The use of Url.For is encouraged as it keeps the details of the actual URL in one place and makes refactoring safer and easier.</p>
<p align="justify"><strong>TodoAddHandler</strong></p>
<p align="justify">When a new to-do item is posted, a request will be made to <strong>/todo/add </strong>with a single value named <em>todo</em> in the request. The <a href="https://github.com/martinrue/Todo-Demo/blob/master/src/Todo/Handlers/Web/TodoAddHandler.cs" target="_blank">TodoAddHandler</a> will then come to the rescue:</p>
<pre class="brush: csharp;">public class TodoAddHandler
{
    IDatabase _database;

    public TodoAddHandler(IDatabase database)
    {
        _database = database;
    }

    public IResult Post(string todo)
    {
        _database.Add(new TodoItem {Text = todo, Date = DateTime.Now});
        _database.Save();

        return Result.Redirect&lt;TodoListHandler&gt;();
    }
}</pre>
<p align="justify">Much like the TodoListHandler, the TodoAddHandler takes a dependency on IDatabase and simply delegates the work of adding the new to-do item to it. After adding the item, the user is redirected back to the TodoListHandler.</p>
<p align="justify">The TodoRemoveHandler, TodoCompleteHandler and TodoUncompleteHandler are all alike, delegating to an IDatabase dependency to perform their single task and redirecting back to the main to-do list afterwards.</p>
<p align="justify"><strong>The API</strong></p>
<p align="justify">The API in this example is just a single end point that gives us back the current to-do list in either JSON or XML format. As you may have noticed before, the <a href="https://github.com/martinrue/Todo-Demo/blob/master/src/Todo/Handlers/API/ApiTodoListHandler.cs" target="_blank">ApiTodoListHandler</a> is exempt (as it’s contained within the <em>allowedHandlers </em>list) from authentication, allowing unauthenticated users to request data from the API.</p>
<pre class="brush: csharp;">public class ApiTodoListHandler
{
    IDatabase _database;

    public ApiTodoListHandler(IDatabase database)
    {
        _database = database;
    }

    public IResult Get()
    {
        return Result.JsonOrXml(_database.GetAll());
    }
}</pre>
<p align="justify">Nothing should be too surprising here – we have a simple handler that supports GET requests at <strong>/api/todo/list </strong>and gives us back the representation we requested via the Accept header or via an extension override.</p>
<p align="justify"><strong>Recap</strong></p>
<p align="justify">And that’s a wrap! We’ve now built the 7 web app handlers that collaborate to form the to-do list and we’ve also created a single API handler which allows the to-do list data to be consumed outside of the core application.</p>
<p align="justify">We’ve implemented error logging inside Tinyweb.OnError by appending log messages to a text file, allowing us to easily diagnose any errors resulting from handlers at runtime.</p>
<p align="justify">Finally, we saw how a global before filter could be used in conjunction with Forms Authentication to ensure that only authenticated users could access particular resources of the system.</p>
<p align="justify">The full to-do demo app can be found at <a href="https://github.com/martinrue/Todo-Demo" target="_blank">https://github.com/martinrue/Todo-Demo</a> if you’d like to play around with it.</p>
<p align="justify"><strong>That’s All Folks</strong></p>
<p align="justify">So, this was the final post in the Tinyweb series and I hope by now it has touched on enough aspects of the framework to give you a good idea of where it sits and what it’s good at. Hopefully, at least one takeaway from this series of posts will be how simple Tinyweb makes building close-to-the-metal web applications – after all, that is Tinyweb’s primary goal.</p>
<p align="justify">I’d love to hear from anyone using the framework and please let me know if you come across any issues or have any suggestions. And remember, Tinyweb is open source and can be forked and contributed to from the <a href="https://github.com/martinrue/Tinyweb" target="_blank">github repository</a>.</p>
<p align="justify">All of the content in this series is also detailed in the <a href="https://github.com/martinrue/Tinyweb/wiki" target="_blank">official documentation</a>, so please check there for any clarifications or <a href="http://twitter.com/martinrue" target="_blank">give me a nudge on Twitter</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://invalidcast.com/2011/05/tinyweb-series-5-to-do-demo/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Tinyweb Series: 4 Views &amp; Model Binding</title>
		<link>http://invalidcast.com/2011/05/tinyweb-series-4-views-model-binding/</link>
		<comments>http://invalidcast.com/2011/05/tinyweb-series-4-views-model-binding/#comments</comments>
		<pubDate>Thu, 12 May 2011 16:28:33 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Projects]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://invalidcast.com/?p=473</guid>
		<description><![CDATA[In the previous post in this series, we looked at Tinyweb’s support for dependency injection and saw how to use both handler and global filters to add processing steps to the execution pipeline. In this post we’re going to see how to render views using the Spark view engine and take a closer look at [...]]]></description>
			<content:encoded><![CDATA[<p align="justify">In the <a href="http://invalidcast.com/2011/05/tinyweb-series-3-dependency-injection-filters" target="_blank">previous post</a> in this series, we looked at Tinyweb’s support for dependency injection and saw how to use both handler and global filters to add processing steps to the execution pipeline.</p>
<p align="justify">In this post we’re going to see how to render views using the <a href="http://sparkviewengine.com/" target="_blank">Spark</a> view engine and take a closer look at how model binding works.</p>
<p>    <span id="more-473"></span>
<p><strong>Views</strong></p>
<p align="justify">We’ve already looked at the various result types that you can return from a handler, but we skipped over arguably the most important one, a view. A view is just HTML, but usually rendered through the use of a templating engine that makes it easier to combine HTML and data.</p>
<p align="justify">You may have played around with different view engines in MSMVC and come across the Spark view engine. If not, don’t worry – it’s fairly easy. Tinyweb ships with support for Spark, so that’s what we’ll use for the examples here.</p>
<p>Let’s see a simple example:</p>
<pre class="brush: csharp;">public class RootHandler
{
    public IResult Get()
    {
        return View.Spark(&quot;Views/Index.spark&quot;);
    }
}</pre>
<p align="justify">We have a pretty typical handler which accepts GET requests at / (the root request) and outputs the Spark view at Views/Index.spark.</p>
<p align="justify">The notable difference from the other result types is that views come from the static class <strong>View</strong>, whereas other results come from <strong>Result </strong>i.e. Result.String. The only reason for this is that simple types and views are considered different and therefore kept separate.</p>
<p align="justify">You’ll notice that the view path starts with a directory named Views. Unlike MSMVC, this is not a convention – it’s just a pattern I tend to follow. If the view file was placed at the root of the application, we could simply return View.Spark(“Index.spark”).</p>
<p align="justify">There’s little point regurgitating the <a href="http://sparkviewengine.com/documentation" target="_blank">Spark documentation</a> in this post, but in case you have never come across Spark before, here’s what a typical view might look like:</p>
<pre class="brush: xml;">&lt;viewdata model=&quot;QuestionAnswerJokes&quot; /&gt;

&lt;ul&gt;
  &lt;li each=&quot;var joke in Model.Jokes&quot;&gt;
    Q: ${joke.Question}
    A: ${joke.Answer}
  &lt;/li&gt;
&lt;/ul&gt;</pre>
<p align="justify">Our contrived view tells Spark that it’s expecting an instance of QuestionAnswerJokes to be passed to it. It then produces an &lt;li&gt; element for each joke contained within the QuestionAnswerJokes.Jokes collection, outputting the question and answer part of each joke into the &lt;li&gt;.</p>
<p align="justify"><em>So, how does it get the model object?</em></p>
<p align="justify"><strong>View Models</strong></p>
<p align="justify">In the handler above, the astute will have noticed that there’s no model being passed to the view. Fear not, I wasn’t trying to hide hideous complexity:</p>
<pre class="brush: csharp;">public class RootHandler
{
    public IResult Get()
    {
        var jokes = JokeService.GetQAJokes();
        return View.Spark(jokes, &quot;Views/JokeList.spark&quot;);
    }
}</pre>
<p align="justify">The view model is simply passed as the first argument to View.Spark, and as long as the model type matches the &lt;viewdata model=”…”/&gt; declaration, we’re good to go.</p>
<p align="justify"><strong>Master Pages</strong></p>
<p align="justify">If we want a view to be part of a master layout, we must specify the master’s name (relative to the location of the view) in the call to View.Spark. This may become cleaner in the future, but for now, it looks like this:</p>
<pre class="brush: csharp;">public class RootHandler
{
    public IResult Get()
    {
        return View.Spark(&quot;Views/Index.spark&quot;, &quot;Master.spark&quot;);
    }
}</pre>
<p align="justify">Rendering views from Tinyweb doesn’t get much more difficult than that, so let’s continue on and take a look at model binding in Tinyweb.</p>
<p align="justify"><strong>Model Binding</strong></p>
<p align="justify">Model binding is the process of automatically taking data from the request (such as the query string or form post data) and mapping that data to the parameters (or properties where a class is used as a parameter) of the handler method. Model binding is useful because it means you write less code and let the framework deal with boring jobs like digging into the request data and populating objects.</p>
<p align="justify">There are three locations that Tinyweb will search for data. It’ll look in the query string, followed by the form post data and finally the route data (which only applies if you are using custom routes with route parameters, see <a href="https://github.com/martinrue/Tinyweb/wiki/Routing" target="_blank">Routing</a>).</p>
<p align="justify">Three types of model binding are currently supported:</p>
<ul>
<li>
<div align="justify">Simple parameters such as <strong>int</strong> and <strong>string</strong></div>
</li>
<li>
<div align="justify">Custom class parameters such as <strong>LoginModel</strong> and <strong>UserSignupModel</strong></div>
</li>
<li>
<div align="justify">Array parameters such as <strong>int[]</strong> and <strong>bool[]</strong></div>
</li>
</ul>
<p align="justify">Let’s go through each one and see an example of where it might be helpful.</p>
<p><strong>Simple Parameters</strong></p>
<pre class="brush: csharp;">public class CalculatorAddHandler
{
    public IResult Get(int first, int second)
    {
        return Result.String((first + second).ToString());
    }
}</pre>
<p align="justify">If we now make a GET request to /calculator/add?first=4&amp;second=2, we should be seeing 6 in the response. In the event no value is sent for <em>first</em> or <em>second</em>, we’ll get an error telling us that required parameters are missing. If you need optional parameters, see the <a href="https://github.com/martinrue/Tinyweb/wiki/Routing" target="_blank">Optional URL Parameters</a> section of the docs (you could also use a custom class, where non-matched properties are just ignored).</p>
<p align="justify"><strong>Custom Class Parameters</strong></p>
<p align="justify">We may also want to use our own classes as parameters to handlers for composing lots of separate fields. For example, If we were implementing a search handler we may want to use a SearchData class to hold the various search options:</p>
<pre class="brush: csharp;">public class SearchData
{
    public string Query { get; set; }
    public bool NewestFirst { get; set; }
}</pre>
<p align="justify">Our handler can now accept an instance of this class, which the model binder will create and populate from the data in the request:</p>
<pre class="brush: csharp;">public class SearchHandler
{
    public IResult Get(SearchData searchData)
    {
        var results = SearchService.Search(searchData);
        return View.Spark(results, &quot;Views/Results.spark&quot;);
    }
}</pre>
<p align="justify">A request to <em>/search?query=help&amp;newestFirst=true</em> will result in the creation of the SearchData object with the relevant properties populated. If the model binder can’t find data for a property, it will simply ignore it without throwing an exception.</p>
<p align="justify"><strong>Array Parameters</strong></p>
<p align="justify">Binding to array parameters can be useful for situations where a collection of values is posted to a handler (via AJAX for example). Let’s assume we have a list of ToDo items in a view and when an item is clicked we toggle an attribute that marks it as complete. Clicking the <em>Save</em> button might run something like the following:</p>
<pre class="brush: js;">var completed = new Array();

$('#todos').each(function() {
    if ($(this).attr('complete') == 'true') {
        completed.push($(this).attr('todoId'));
    }
});

$.post('/todo/delete', { Completed: completed }, function() {
    alert('Saved');
});</pre>
<p align="justify">The script builds up an array of numbers and posts them to /todo/delete. A handler can receive the collection like this:</p>
<pre class="brush: csharp;">public class TodoDeleteHandler
{
    public IResult Post(int[] completed)
    {
        var deleted = TodoService.DeleteMany(completed);
        return Result.JsonOrXml(deleted);
    }
}</pre>
<p><strong>Special Binding Cases</strong></p>
<p align="justify">Tinyweb’s model binder has two special cases where the handler or filter can get access to either the RequestContext or the HandlerData for the current request.</p>
<p align="justify">The RequestContext gives you access to the underlying ASP.NET infrastructure (the HttpContext – <em>please, don’t run away, come back</em>) and means you can do anything that you’d do from within a raw HttpHandler, such as access the Request, Response, Cache and Session collections.</p>
<p align="justify">HandlerData is a class from tinyweb.framework that holds the handler’s System.Type and its URL, in addition to any default route values it has defined. Accessing HandlerData is useful more so in filters where the handler for the current request needs to be identified for things like logging.</p>
<p align="justify">The model binder will supply RequestContext and HandlerData to any handler or filter that declares a parameter of either type.</p>
<p><strong>Model Binding Limitations</strong></p>
<p align="justify">As of version 2.1.0 of Tinyweb, the model binder provides no way to exclude individual properties from model binding. The recommended practice is to use a type specifically crafted for receiving only the data you care about from model binding. The next release will add support for binding exclusions, addressing those situations where you wish to bind to existing objects but restrict the binding scope.</p>
<p align="justify"><strong>EDIT </strong>As of version 2.1.2, binding exclusions are supported via use of the <em>[Ignore] </em>attribute on class members that should be excluded from model binding. See <a href="https://github.com/martinrue/Tinyweb/wiki/Model-Binding" target="_blank">model binding</a> for more information.</p>
<p><strong>In This Post</strong></p>
<p align="justify">We looked at rendering Spark views and touched on how to use view models and master layouts. We then focused on model binding in a little more depth, looking at each of the three (simple, complex &amp; array) types of binding supported and – <em>as is tradition at this point</em> – built a couple of contrived examples to demonstrate the point. Finally, we saw the two special binding cases for getting access to RequestContext and HandlerData.</p>
<p align="justify">Keep in mind that everything we’ve covered so far is also covered in the <a href="https://github.com/martinrue/Tinyweb/wiki" target="_blank">documentation</a>, which is the best place to go if you require clarification. Failing that, I’ve been known to <a href="http://twitter.com/martinrue" target="_blank">tweet once or twice</a>.</p>
<p><strong>In The Final Post</strong></p>
<p align="justify">We’ll put together a few of the things talked about so far and build a ToDo application, dealing with things like API access, authentication and logging. We may even get time to do some benchmarking.</p>
]]></content:encoded>
			<wfw:commentRss>http://invalidcast.com/2011/05/tinyweb-series-4-views-model-binding/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Tinyweb Series: 3 Dependency Injection &amp; Filters</title>
		<link>http://invalidcast.com/2011/05/tinyweb-series-3-dependency-injection-filters/</link>
		<comments>http://invalidcast.com/2011/05/tinyweb-series-3-dependency-injection-filters/#comments</comments>
		<pubDate>Wed, 11 May 2011 16:17:45 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Projects]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://invalidcast.com/?p=465</guid>
		<description><![CDATA[In the previous post in this series, we looked at how Tinyweb can be used to build HTTP APIs and examined each of the result types a handler may return. The examples in the last post used made-up dependencies and you may have wondered how does the handler get these dependencies? In this post, we’ll [...]]]></description>
			<content:encoded><![CDATA[<p align="justify">In the <a href="http://invalidcast.com/2011/05/tinyweb-series-2-building-apis" target="_blank">previous post</a> in this series, we looked at how Tinyweb can be used to build HTTP APIs and examined each of the result types a handler may return.</p>
<p align="justify">The examples in the last post used made-up dependencies and you may have wondered <em>how does the handler get these dependencies?</em> In this post, we’ll look at how easy it is to have dependencies injected into handlers. We’ll also take a look at the use of filters to facilitate things like logging and error handling.</p>
<p>  <span id="more-465"></span>
<p><strong>Dependency Injection</strong></p>
<p align="justify">We probably all know what dependency injection is, but let’s just clarify. Assume we have a UserService which implements IUserService, allowing us to invert the dependency (<a href="http://en.wikipedia.org/wiki/Solid_(object-oriented_design)" target="_blank">SOLI<strong>D</strong></a>). In a handler (or filter), we need access to an instance of UserService, but we can’t create one directly as we’d violate <a href="http://en.wikipedia.org/wiki/Dependency_inversion_principle" target="_blank">DIP</a>. Instead we need a container to create the dependency chain for us. We simply depend on the interface and leave the dependency construction to the container.</p>
<p align="justify">Let’s see how we can do this in Tinyweb.</p>
<p align="justify">In line with its goal of keeping things as simple as possible, Tinyweb takes a dependency on <a href="http://structuremap.net/structuremap/" target="_blank">StructureMap</a> in order to support dependency injection out of the box. This means that all you need to do is create StructureMap registries and tell Tinyweb about them – the rest will be handled by the framework.</p>
<p align="justify">Using the UserService example from above, let’s assume we have the following:</p>
<pre class="brush: csharp;">public interface IUserService
{
    User GetById(int id);
}

public class UserService : IUserService
{
    public User GetById(int id)
    {
        // find the user and return it
    }
}</pre>
<p align="justify">The next thing we need to do is create a StructureMap registry which associates these two, like so:</p>
<pre class="brush: csharp;">public class ServiceRegistry : Registry
{
    public ServiceRegistry()
    {
        Scan(x =&gt;
        {
            x.TheCallingAssembly();
            x.WithDefaultConventions();
        });
    }
}</pre>
<p align="justify">The ServiceRegistry tells StructureMap that interfaces IFoo and IBar in the current assembly should have concrete types called Foo and Bar respectively.</p>
<p align="justify">We need to tell Tinyweb about this registry for it to be&#160; able to construct handlers that have constructor dependencies. Registering them is as easy as passing them to Tinyweb.Init, like so:</p>
<pre class="brush: csharp;">protected void Application_Start(object sender, EventArgs e)
{
    Tinyweb.Init(new ServiceRegistry());
}</pre>
<p align="justify">Internally Tinyweb associates any registries with StructureMap, which it then uses to create handlers when requests come in. This allows us to create handlers with abstract dependencies and have the framework deal with it for us:</p>
<pre class="brush: csharp;">public class UsersAddHandler
{
    IUserService _userService;

    public UsersAddHandler(IUserService userService)
    {
        _userService = userService;
    }

    public IResult Post(User user)
    {
        var added = _userService.Add(user);
        return Result.JsonOrXml(added);
    }
}</pre>
<p align="justify">When a POST request is made to /users/add, the framework will create an instance of the UsersAddHandler using StructureMap, and because we have registered the ServiceRegistry the IUserService dependency will be supplied as a concrete UserService.</p>
<p align="justify"><strong>Filters</strong></p>
<p align="justify">Moving on, let’s take a look at <a href="https://github.com/martinrue/Tinyweb/wiki/Filters" target="_blank">filters</a> and see how they let us plug into the execution pipeline of a request. Tinyweb supports both handler filters and global filters. A handler filter is a Before or After method on the handler which is run before or after the intended HTTP method is run, like so:</p>
<pre class="brush: csharp;">public class RootHandler
{
    public IResult Before()
    {
        return Result.String(&quot;Before the request...&quot;);
    }

    public IResult Get()
    {
        return Result.String(&quot;Root request&quot;);
    }

    public IResult After()
    {
        return Result.String(&quot;After the request...&quot;);
    }
}</pre>
<p align="justify">Notice how the two filters also return IResult, allowing them to affect the response. Filters can have void return types if they don’t wish to add anything to the response. The example above, predictably, outputs the following:</p>
<pre class="brush: plain;">Before the request...
Root request
After the request...</pre>
<p align="justify">Filters also have the same model binding support that handler methods have, allowing a filter to log events using data from the request, for example:</p>
<pre class="brush: csharp;">public class UsersDeleteHandler
{
    public IResult Post(int id)
    {
        var deleted = UserService.Delete(id);
        return Result.JsonOrXml(deleted);
    }

    public void After(int id)
    {
        Logger.Log(&quot;Deleted user &quot; + id);
    }
}</pre>
<p align="justify">Since we’re simply logging that a user has been deleted, we don’t use the IResult return type on the After filter.</p>
<p align="justify">To recap, handler filters are just well defined ways of running code just prior or just after a handler method is executed. Let’s move on and have a look at global filters.</p>
<p align="justify">Tinyweb also supports global filters that apply to all handlers, which is useful for system-level logging or performance monitoring. Use a global filter when something needs to happen before or after every request.</p>
<p align="justify">Like handler filters, global filters also support model binding – though it may not be very useful for situations where you’re logging every request (as you wouldn’t know which request and hence what required data has been sent).</p>
<p align="justify">Global filters are just like handler filters except they must exist in a separate class which ends with the word Filter. MyLogging<strong>Filter</strong> would be discovered as a valid filter (as long as it had a Before or After method), whereas MyLoggerFilterClass would not be found because it doesn’t end with the word Filter.</p>
<p>Let’s see an example:</p>
<pre class="brush: csharp;">public class TimingFilter
{
    Stopwatch timer;

    public void Before()
    {
        timer = Stopwatch.StartNew();
    }

    public IResult After()
    {
        timer.Stop();
        return Result.String(&quot;Time: &quot; + timer.ElapsedMilliseconds);
    }
}</pre>
<p align="justify">This filter adds the <em>Time: xxxx </em>message to the bottom of every request, allowing us to see how quickly each request executes.</p>
<p align="justify">Global filters can also get access to the underlying RequestContext (from ASP.NET) and the HandlerData – Tinyweb’s internal structure used to identify the intended handler. If we wanted to create a list of every handler that was requested, we could use a global filter with HandlerData to do it:</p>
<pre class="brush: csharp;">public class RequestLoggingFilter
{
    public void After(HandlerData handler)
    {
        Logger.Log(&quot;Request completed to &quot; + handler.Type);
    }
}</pre>
<p align="justify">Finally, in terms of logging errors, this can be dealt with by supplying a delegate to Tinyweb.OnError which will receive the exception, the RequestContext and the HandlerData for the offending handler, like so:</p>
<pre class="brush: csharp;">protected void Application_Start(object sender, EventArgs e)
{
    Tinyweb.Init();

    Tinyweb.OnError = (exception, request, handler) =&gt;
    {
        Logger.Log(exception + &quot; error for &quot; + handler.Type);
    }
}</pre>
<p align="justify">See the <a href="https://github.com/martinrue/Tinyweb/wiki/Error-Logging" target="_blank">documentation</a> for more details about error logging with the OnError delegate.</p>
<p align="justify"><strong>In This Post</strong></p>
<p align="justify">We saw how Tinyweb makes injecting dependencies into handlers (and filters) easy through its internal use of StructureMap. We then moved onto filters and saw how Tinyweb supports filtering at both the handler level and globally. </p>
<p align="justify">We then walked through a couple of demos showing how we can use global filters for logging and timing requests. Finally we saw a brief example of how error logging can be achieved using Tinyweb.OnError.</p>
<p align="justify"><strong>In The Next Post</strong></p>
<p align="justify">We’ll see how to use the <a href="http://sparkviewengine.com/" target="_blank">Spark</a> view engine and take a closer look at model binding.</p>
]]></content:encoded>
			<wfw:commentRss>http://invalidcast.com/2011/05/tinyweb-series-3-dependency-injection-filters/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Tinyweb Series: 2 Building APIs</title>
		<link>http://invalidcast.com/2011/05/tinyweb-series-2-building-apis/</link>
		<comments>http://invalidcast.com/2011/05/tinyweb-series-2-building-apis/#comments</comments>
		<pubDate>Tue, 10 May 2011 19:00:00 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Projects]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://invalidcast.com/?p=444</guid>
		<description><![CDATA[In the previous post in this series, I gave an introduction to the Tinyweb project and walked through a demonstration of how to get started. We took a brief look at how handlers return content to the client, but in today’s post we’ll take a more in-depth look at how this works. Returning Data From [...]]]></description>
			<content:encoded><![CDATA[<p align="justify">In the <a href="http://invalidcast.com/2011/05/tinyweb-series-1-getting-started" target="_blank">previous post</a> in this series, I gave an introduction to the Tinyweb project and walked through a demonstration of how to get started.</p>
<p align="justify">We took a brief look at how handlers return content to the client, but in today’s post we’ll take a more in-depth look at how this works.</p>
<p>    <span id="more-444"></span>
<p align="justify"><strong>Returning Data From Handlers</strong></p>
<p align="justify">In case you can’t remember, here’s a typical Tinyweb handler which processes HTTP GET requests at the URL /users/create and returns an HTML view:</p>
<pre class="brush: csharp;">public class UsersCreateHandler
{
    public IResult Get()
    {
        return View.Spark(&quot;Views/Signup.spark&quot;);
    }
}</pre>
<p align="justify">The UsersCreateHandler is simply rendering a <a href="http://sparkviewengine.com" target="_blank">Spark</a> view when a request is made to /users/create, providing the client with an HTML form to sign up. Let’s take a look at what else we can return from handlers.</p>
<p><strong>The Result Class</strong></p>
<p align="justify">To make handler result types more discoverable, you can use the static Result class to create them. This also serves the purpose of making any generic uses of the result types cleaner. Currently we have the following members in Result:</p>
<pre class="brush: plain;">Result.None
Result.String
Result.Html
Result.File
Result.Json
Result.Xml
Result.JsonOrXml
Result.Redirect&lt;T&gt;</pre>
<p align="justify">Let’s look at each one and see what it can be used for.</p>
<p align="justify"><strong>Result.None</strong></p>
<p align="justify"><em>No result? </em>It may initially throw you, but the purpose of Result.None is to process a request without affecting the response body. Result.None exists to support two situations:</p>
<ul>
<li>
<div align="justify">Filters that don’t wish to affect the response in any way. </div>
</li>
<li>
<div align="justify">Handlers that are to be treated in a fire-and-forget manner, where the response doesn’t matter. </div>
</li>
</ul>
<p align="justify">We haven’t looked at filters yet, but here’s a contrived example for the fire-and-forget usage of Result.None:</p>
<pre class="brush: csharp;">public class ServerRebootHandler
{
    public IResult Get()
    {
        TheServer.Reboot();
        return Result.None();
    }
}</pre>
<p align="justify">A caller just wants to signal that the server should be rebooted (don’t ask me why we’d want this, it’s contrived people) and not care about any result, so the handler returns Result.None so that it won’t waste time adding anything to the response body.</p>
<p align="justify"><strong>Result.String</strong></p>
<p align="justify">We’ve seen this in some of the demos, and it’s fairly self explanatory. Result.String returns a raw string with an HTML content type, causing the browser to render any content as normal. It’s not something you’d use in an API or a web application necessarily, but it’s useful for diagnostics and situations where you just need to output simple things.</p>
<p align="justify"><strong>Result.Html</strong></p>
<p align="justify">Result.Html is essentially the same as Result.String but it takes the data from a disk file instead of a raw string. Not especially exciting.</p>
<p align="justify"><strong>Result.File</strong></p>
<p align="justify">Admittedly, this is becoming quite predictable now. Yes, Result.File allows you to send a file back in the response, causing a browser to show the familiar <em>Save File</em> dialog.</p>
<p align="justify"><strong>Result.Json and Result.Xml</strong></p>
<p align="justify">Keeping with the theme of blatantly obvious, both these types do exactly what you might expect. Let’s see some more code:</p>
<pre class="brush: csharp;">public class UserDetailsHandler
{
    public IResult Get(int userId)
    {
        return Result.Json(UserService.GetById(userId));
    }
}</pre>
<p>A request to /users/details/42 might return a JSON representation of the user object, like so:</p>
<pre class="brush: js;">{
  &quot;ID&quot;:42,
  &quot;Username&quot;:&quot;Igor&quot;,
  &quot;Age&quot;:62
}</pre>
<p align="justify">Replacing Result.Json with Result.Xml would have the expected effect, and we’d be seeing beautiful XML in place of that horrible JSON. Erm<em>, I think I got that right.</em></p>
<p align="justify">As a side note, you may be wondering about the parameter in the handler method. Tinyweb supports <a href="https://github.com/martinrue/Tinyweb/wiki/Model-Binding" target="_blank">model binding</a> of simple, complex and array types and will supply values to the handler that were found in the request or route data. We’ll look into this more in a future post.</p>
<p><strong>Result.Redirect&lt;T&gt;</strong></p>
<p align="justify"><em>Stop – you missed one.</em></p>
<p align="justify"><em>I’ll come to Result.JsonOrXml in a second, which will take us nicely into the discussion about building APIs with Tinyweb.</em></p>
<p align="justify">As I was saying – Result.Redirect&lt;T&gt; allows us to redirect from one handler to another. It kind of goes without saying that this is important, since otherwise there’d be no way for us to pass control between handlers to form more complex behaviours.</p>
<p align="justify">Result.Redirect&lt;T&gt; takes the handler type as the generic parameter, giving us some safety for future changes to handler names and such refactorings. There’s also a version that you can pass a raw URL to, if you so wish.</p>
<p align="justify">Quick example:</p>
<pre class="brush: csharp;">public class CuteKittensHandler
{
    public IResult Get()
    {
        GullibilityCount++;
        return Result.Redirect&lt;RickHandler&gt;();
    }
}

public class RickHandler
{
    public IResult Get()
    {
        return Result.Redirect(&quot;http://bit.ly/4kb77v&quot;);
    }
}</pre>
<p align="justify"><em>Don’t blame me, the signs were there all along.</em></p>
<p align="justify"><strong>Result.JsonOrXml</strong></p>
<p align="justify">And finally we come to Result.JsonOrXml. The point of this type is to return the resource in a format that is preferred by the client. Clients typically specify this using the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html" target="_blank">Accept</a> header, but Tinyweb also allows <a href="https://github.com/martinrue/Tinyweb/wiki/Building-APIs" target="_blank">Extension Overrides</a> to make it easier.</p>
<p align="justify">Let’s look at the role Result.JsonOrXml plays in building JSON and XML APIs using Tinyweb.</p>
<p align="justify"><strong>Building APIs</strong></p>
<p align="justify">Because Tinyweb enforces a development model where each handler can only support the basic HTTP methods for a single URL, we get lots of small, well defined handlers forming a system. This decoupling and focus on single responsibility works well for building web applications, but especially well for building HTTP APIs.</p>
<p align="justify">Let’s improvise another contrived example and build an HTTP API. We’ll assume the API is going to support a rich client in the browser, but also some legacy systems which require XML representations. In other words, we’ll be supporting both JSON and XML responses.</p>
<p align="justify">The API will allow us to manage a set of users via three resources, /users/add, /users/delete and /users/view for adding, deleting and viewing users respectively.</p>
<pre class="brush: csharp;">public class UsersAddHandler
{
    public IResult Post(User user)
    {
        UserService.Add(user);
        return Result.JsonOrXml(user);
    }
}

public class UsersDeleteHandler
{
    public IResult Post(int id)
    {
        var deleted = UserService.Delete(id);
        return Result.JsonOrXml(deleted);
    }
}

public class UsersViewHandler
{
    public IResult Get(int id)
    {
        var user = UserService.Get(id);
        return Result.JsonOrXml(user);
    }
}</pre>
<p align="justify">Let’s have a look at each handler and see what’s going on.</p>
<p align="justify">First we have the UsersAddHandler which supports POST requests at /users/add. Any POST data that matches properties on the User object will be model bound automatically by Tinyweb.</p>
<p align="justify">The UsersAddHandler is pretty simple, it just creates a user by delegating to UserService.Add and then returns a representation of the new user back to the client.</p>
<p align="justify">Next we have the UsersDeleteHandler which is very much the same, supporting POST requests at /users/delete to remove users. This handler returns a representation of the true/false return value from UserService.Delete, indicating whether the user was deleted.</p>
<p align="justify">Finally, the UsersViewHandler returns a representation of the requested user at /users/view.</p>
<p align="justify"><strong>The Accept Header</strong></p>
<p align="justify">As mentioned earlier, a handler that returns Result.JsonOrXml is specifying that the actual representation can be JSON or XML, depending on which is requested by the client via the Accept header. For example, if the UsersViewHandler is requested like this:</p>
<pre class="brush: csharp;">GET /users/view?id=42 HTTP/1.1
Accept: application/xml;q=0.8,application/json;q=0.7</pre>
<p align="justify">Because the Accept header is preferring application/xml over application/json, Tinyweb will return an XML representation of the user. If it was requested with a preference for JSON over XML, the reverse would happen. Tinyweb defaults to JSON if no preference can be determined.</p>
<p align="justify"><strong>Extension Overrides</strong></p>
<p align="justify">In addition to the Accept header, Tinyweb can be configured to use <a href="https://github.com/martinrue/Tinyweb/wiki/Building-APIs" target="_blank">Extension Overrides</a> which allow a URL extension to be used to control the preferred response type. For this to work, you’ll need to set AllowFormatExtensions to true during initialisation, like so:</p>
<pre class="brush: csharp;">protected void Application_Start(object sender, EventArgs e)
{
    Tinyweb.AllowFormatExtensions = true;
    Tinyweb.Init();
}</pre>
<p align="justify">Now the same resource can be requested without the Accept header by appending either a .xml or .json extension to the URL, i.e. /users/view.json?id=42 or /users/view.xml?id=42. This makes debugging easier and some people prefer the more discoverable method of specifying response types in the URL.</p>
<p align="justify"><strong>In This Post</strong></p>
<p align="justify">We looked at Tinyweb’s various response types and considered what they are useful for. In particular we saw how Result.Redirect&lt;T&gt; allows us to pass control between handlers in order to compose groups of handlers into more complex behaviours – albeit in a somewhat contrived example.</p>
<p align="justify">We then looked at how Tinyweb is suited to building HTTP APIs and looked at how Result.JsonOrXml allows us to defer specification of the response type to the client through the Accept header or through URL extensions.</p>
<p align="justify"><strong>In The Next Post</strong></p>
<p align="justify">We’ll take a look at how Tinyweb tackles dependency injection with StructureMap and how we can use handler and global filters to extend the execution pipeline for things like logging and error handling.</p>
]]></content:encoded>
			<wfw:commentRss>http://invalidcast.com/2011/05/tinyweb-series-2-building-apis/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Tinyweb Series: 1 Getting Started</title>
		<link>http://invalidcast.com/2011/05/tinyweb-series-1-getting-started/</link>
		<comments>http://invalidcast.com/2011/05/tinyweb-series-1-getting-started/#comments</comments>
		<pubDate>Mon, 09 May 2011 18:00:00 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Projects]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://invalidcast.com/?p=437</guid>
		<description><![CDATA[Tinyweb is an open source project I started last November with the goal of creating a minimal, service-oriented web application framework. I’ve been committing to the project ever since and it has now reached a level of maturity I’m happy with. Full documentation for the project was completed recently and I figure it’s time to [...]]]></description>
			<content:encoded><![CDATA[<p align="justify"><a href="http://nuget.org/List/Packages/Tinyweb" target="_blank">Tinyweb</a> is an open source project I started last November with the goal of creating a minimal, service-oriented web application framework. <a href="https://github.com/martinrue/Tinyweb" target="_blank">I’ve been committing</a> to the project ever since and it has now reached a level of maturity I’m happy with.</p>
<p align="justify"><a href="https://github.com/martinrue/Tinyweb/wiki" target="_blank">Full documentation</a> for the project was completed recently and I figure it’s time to write a <em>how to</em> series of posts that cover the most interesting aspects of the framework.</p>
<p align="justify">So here we are with the first instalment. My goal for part 1 is to explain the thinking behind the project and show you how easy it is to <em>file –&gt; new project</em>.</p>
<p>  <span id="more-437"></span>
<p><strong>What’s Tinyweb?</strong></p>
<p>From the docs:</p>
<blockquote><p>Tinyweb is a lightweight web framework for ASP.NET that embraces HTTP and aims to be ridiculously simple.</p>
</blockquote>
<p align="justify">Approaching the project with a background in using the MVC pattern, my goal was to move away from the issue of <a href="http://codebetter.com/iancooper/2008/12/03/the-fat-controller/" target="_blank">fat controllers</a> and provide less abstraction over the core functionality of HTTP.</p>
<p align="justify">In Tinyweb, the URL, or more precisely the <a href="http://invalidcast.com/2011/03/asp-net-thinking-in-resources" target="_blank">resource</a> is the starting concept. By resource, I mean a single entity addressable by its URL and able to respond to any of the standard HTTP methods. </p>
<p align="justify">The resource is just a simple class with methods for each HTTP method it wishes to respond to, for example:</p>
<pre class="brush: csharp;">public class SignupHandler
{
    IUserService _userService;

    public SignupHandler(IUserService userService)
    {
        _userService = userService;
    }

    public IResult Get()
    {
        return View.Spark(&quot;Views/Signup.spark&quot;);
    }

    public IResult Post(UserModel user)
    {
        _userService.CreateUser(user);
        return Result.Redirect&lt;WelcomeHandler&gt;();
    }
}</pre>
<p align="justify">Because the Signup<em>Handler</em> has a single URL and can only respond to the core HTTP methods, a certain level of SRP is enforced by this model. Tinyweb encourages an application to be broken into separate resources that collectively form a coherent system.</p>
<p align="justify">Tinyweb leans more toward a service-oriented approach to building web applications, where every endpoint within the system has a well defined purpose and collaboration between endpoints is used to form more complex behaviours. This is particularly fitting for pure JSON or XML APIs and I’ll be covering some related features of Tinyweb later in the series.</p>
<p align="justify">Another underlying goal of Tinyweb is simplicity. The framework itself is small, with a tiny pipeline and simple conventions to save you having lots of configuration. Conventions aren’t concrete and can be overridden, but using Tinyweb should to be fun, easy and consistent.</p>
<p><strong>File –&gt; New Project</strong></p>
<p align="justify">So, let’s see how we create a new project using Tinyweb.</p>
<p align="justify">We’ll need an empty project to start with, so go ahead and create a new <em>ASP.NET Empty Web Application</em> project in Visual Studio. <em>Done it?</em></p>
<p align="justify">OK, next we need to install the latest version of Tinyweb using the wonderful NuGet. Open the <em>Package Manager Console</em> and cast this spell:</p>
<pre class="brush: plain;">Install-Package Tinyweb</pre>
<p align="justify">NuGet will go and grab the relevant assemblies and add them to your exciting new empty project. Once done, Tinyweb is installed and ready for us to start writing some code.</p>
<p align="justify">Fortunately Tinyweb doesn’t require you to add anything to the web.config. Instead, Tinyweb is initialised from within Global.asax. You won’t have one yet, so you’ll need to add a new Global.asax file to your project. After you’ve added it, initialise Tinyweb like so:</p>
<pre class="brush: csharp;">protected void Application_Start(object sender, EventArgs e)
{
    Tinyweb.Init();
}</pre>
<p align="justify">That wasn’t too painful, was it? Tinyweb is now loaded and routes have been configured to the various handlers that were discovered. There are other things you can do at this point, but we’ll cover them later in the series. For now, this is all you need.</p>
<p align="justify"><strong>The Handler</strong></p>
<p align="justify">All the required setup and initialisation is done, and we’re now ready to build our actual application. Since this is Tinyweb land, we need to think about the first resource our system will need. Given this is the introduction post, and I’m creatively numb, let’s be traditional. The first handler will respond to HTTP GET requests at /hello/world and respond with the message <em>Hello World</em>. <em>Exciting huh? Just me then?</em></p>
<pre class="brush: csharp;">public class HelloWorldHandler
{
    public IResult Get()
    {
        return Result.String(&quot;Hello World&quot;);
    }
}</pre>
<p><em></em></p>
<p align="justify">Pretty simple, but let’s break it down and understand what’s going on here.</p>
<p align="justify"><strong>The Handler Name</strong></p>
<p align="justify">Firstly, notice how the class doesn’t implement any base or interface. A handler is a handler if it ends in <strong>Handler</strong>. <em>Say that fast 10 times</em>. When <strong>Tinyweb.Init</strong><em> </em>is called, handlers are discovered by scanning for classes that end with the word <strong>Handler</strong>. There’s the first convention.</p>
<p align="justify">The first part of the handler name is significant too. Breaking it up into its constituent <a href="http://c2.com/cgi/wiki?PascalCase" target="_blank">Pascal-cased</a> words, the handler name is used to build the URL of the resource. Because our handler is named <strong>HelloWorld</strong>Handler, Tinyweb produces the URL /hello/world. </p>
<p align="justify">Had the handler been called <strong>Home</strong>Handler, we’d have the URL /home, or <strong>YabaDabaDoo</strong>Handler would be addressable at /yaba/daba/doo. There’s the second convention.</p>
<p align="justify"><strong>The Handler Method</strong></p>
<p align="justify">Next we have the method itself. Tinyweb recognises four potential methods which mirror the underlying HTTP methods, i.e. <strong>Get</strong>, <strong>Post</strong>, <strong>Put</strong> and <strong>Delete</strong>. You can also have <strong>Before </strong>and <strong>After </strong>methods, but we’ll talk about those later in the series.</p>
<p align="justify">Notice how the method returns <strong>IResult</strong>. This is the interface used to represent a handler response. Handlers must have a return type of <strong>IResult</strong> to be properly discovered. Tinyweb supports a number of result types including Result.String, Result.Json and View.Spark and we’ll look at these in the next post.</p>
<p align="justify">Finally, the handler returns a value to the client by using the static <strong>Result</strong> class. <strong>Result </strong>provides access to the supported result types while <strong>View </strong>provides access to the supported set of view engine results. Tinyweb currently ships with support for the <a href="http://sparkviewengine.com" target="_blank">Spark view engine</a>.</p>
<p><strong>In This Post</strong></p>
<p align="justify">I introduced Tinyweb – the minimal web framework that encourages the use of concepts from HTTP to build service-style applications using ASP.NET. I talked about Tinyweb’s core goal of simplicity and explained how Tinyweb makes use of conventions and discovery to keep your code as simple as possible.</p>
<p align="justify">We built an example application, demonstrating how to install, initialise and write our first handler. We then dug a bit deeper into the method used for generating handler URLs and looked at what a handler can do.</p>
<p align="justify"><strong>Until Next Time</strong></p>
<p align="justify">If you want to dive in and have a play around, simply install Tinyweb from <a href="http://nuget.org/List/Packages/Tinyweb" target="_blank">NuGet</a>, check out the <a href="https://github.com/martinrue/Tinyweb/wiki" target="_blank">documentation</a> and if you have any questions, <a href="http://twitter.com/martinrue" target="_blank">I’d be happy to help</a>.</p>
<p align="justify">Next time we’ll look at the different types of content that can be returned by a handler, and look specifically at some features which are aimed at building JSON/XML APIs.</p>
]]></content:encoded>
			<wfw:commentRss>http://invalidcast.com/2011/05/tinyweb-series-1-getting-started/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>The Zone</title>
		<link>http://invalidcast.com/2011/04/the-zone/</link>
		<comments>http://invalidcast.com/2011/04/the-zone/#comments</comments>
		<pubDate>Sat, 23 Apr 2011 22:44:51 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Observations]]></category>

		<guid isPermaLink="false">http://invalidcast.com/2011/04/the-zone/</guid>
		<description><![CDATA[As programmers, the zone is something we are all aware of but something that we rarely explore. Yet we’ve all been there – totally focused and producing the best work we could have hoped for. To some, the zone is seen as some kind of rare Zen state. Some think it’s a myth that doesn’t [...]]]></description>
			<content:encoded><![CDATA[<p align="justify"><img style="background-image: none; border-right-width: 0px; margin: 0px 0px 0px 10px; padding-left: 0px; padding-right: 0px; display: inline; float: right; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" border="0" align="right" src="http://www.zenventory.com/images/zenman.jpg" width="68" height="67" />As programmers, the zone is something we are all aware of but something that we rarely explore. Yet we’ve all been there – totally focused and producing the best work we could have hoped for.</p>
<p align="justify">To some, the zone is seen as some kind of rare Zen state. Some think it’s a myth that doesn’t actually exist. Either way, it’s understandable that there are so many different opinions; it’s not an easy thing to objectively discuss.</p>
<p align="justify">But, what the hell – here’s what I think.</p>
<p>  <span id="more-429"></span>
<p align="justify">In actual fact, the zone is nothing to do with programming – though it is a term that’s used much more often in this context. Being in the zone is just a condensed version of:</p>
<ul>
<li>
<div align="justify">Having a good understanding of the task</div>
</li>
<li>
<div align="justify">Feeling as though you have the dedication and skill to complete the task</div>
</li>
<li>
<div align="justify">Being able to concentrate </div>
</li>
<li>
<div align="justify">Feeling happy in yourself and your environment</div>
</li>
</ul>
<p align="justify">These are not simple states; being able to concentrate might be a combination of a quiet atmosphere and a good music playlist, or perhaps a tidy desk and no interruptions. There are lots of subjective elements of each of these states, but none of them are inherently difficult to achieve.</p>
<p align="justify">If you understand exactly what you need to do, know how to do it, know that you actually want to do it and can remain focused, the zone comes quite naturally.</p>
<p align="justify">But I think we can simplify this into something more fundamental.</p>
<p align="justify">Back in college, I did not like mathematics at all. I enjoyed the application of concepts rooted in mathematics, but the study of abstract things on their own totally disengaged me. But don’t worry, I wasn’t a total failure – I did well in other subjects, and it’s no coincidence I enjoyed them more.</p>
<p align="justify">Enjoyment has wonderful side effects. It’s much easier to focus on something you enjoy. It also requires much less effort to develop skills in subjects you enjoy; they sometimes even appear to develop transparently. And fairly obviously, it’s easier to achieve happiness through doing things you enjoy. </p>
<p align="justify">This is nothing new:</p>
<blockquote><p align="justify">Success in highest and noblest form calls for peace of mind and enjoyment and happiness which comes only to the man who has found the work he likes best.</p>
<p align="justify">– Napoleon Hill</p>
</blockquote>
<p align="justify">If we are lucky enough to be working on something we enjoy, the points above all become side effects of the fact that we’re enjoying ourselves. If we’re struggling to find the zone, we should look for opportunities to make what we’re doing more interesting. This will improve the chances of being able to focus and finding the required inspiration.</p>
<p align="justify">If we don’t enjoy what we’re doing, it’s unlikely we’ll find the zone without a good amount of self discipline. Maintaining focus and dedication, and building understanding without the catalyst of enjoyment is the reason people tend to do worse at things they hate and better at things they love.</p>
<p align="justify">There isn’t just one zone, there are many zones each competing for our attention. It’s not a coincidence that those who can’t get into the zone are telling us about it on Twitter. In fact, they have found the zone. They’re in the zone of socialising, which is a pretty easy zone to get into since it’s very enjoyable, but is it the zone you want to be in?</p>
<p align="justify">The zone is not some unachievable state of Zen, reserved only for the enlightened ones. You don’t need to sit with your legs crossed, humming, waiting for it to bless you with the ability to do awesome things – you already have that ability.</p>
<p align="justify">The zone is just a fancy-ass way of describing the required focus and dedication you need to do something to the best of your ability. When you enjoy what you’re doing, these things happen much more naturally. When you don’t, you need to compensate with discipline, and your mileage certainly may vary.</p>
<p align="justify">The zone isn’t random and it isn’t a myth – you can create it as often as you like.</p>
]]></content:encoded>
			<wfw:commentRss>http://invalidcast.com/2011/04/the-zone/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Sentiment Analysis Talk</title>
		<link>http://invalidcast.com/2011/04/sentiment-analysis-talk/</link>
		<comments>http://invalidcast.com/2011/04/sentiment-analysis-talk/#comments</comments>
		<pubDate>Sun, 17 Apr 2011 22:02:00 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Events]]></category>

		<guid isPermaLink="false">http://invalidcast.com/2011/04/sentiment-analysis-talk/</guid>
		<description><![CDATA[Today I gave a talk about textual sentiment analysis at BarCamp Sheffield. Here’s a summary of the talk and links to the slides, demo and code. Sentiment analysis is the process of analysing data to determine its sentiment, or mood. It’s an important area of research as it relates to improving things like customer satisfaction [...]]]></description>
			<content:encoded><![CDATA[<p align="justify"><img style="background-image: none; border-right-width: 0px; margin: 0px 0px 0px 10px; padding-left: 0px; padding-right: 0px; display: inline; float: right; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" border="0" align="right" src="http://euroross.blogspot.com/Happy%20Sad.jpg" width="158" height="137" />Today I gave a talk about textual sentiment analysis at BarCamp Sheffield. Here’s a summary of the talk and links to the slides, demo and code.</p>
<p align="justify">Sentiment analysis is the process of analysing data to determine its sentiment, or mood. It’s an important area of research as it relates to improving things like customer satisfaction and making advertising more effective.</p>
<p>  <span id="more-422"></span>
<p align="justify">Sentiment analysis can add certain meaning to data and move us away from the simple keyword matching that we currently use. However, it’s a difficult problem to solve with around a 70% agreement rate between human analysers. </p>
<p align="justify">The simplest implementations tend to be things like <em>bag of words </em>where a collection of known positive and negative words are manually maintained and a subject is classified by calculating which collection has the most matches.</p>
<p align="justify">These word lists don’t scale well however. Much effort is needed to keep them up to date and deal with things such as misspellings and grammar errors. When you factor in context, which can often change the meaning, you’re left writing rules around the bag of words to capture those situations.</p>
<p align="justify">When you’re aiming to analyse data from a wide set of possible sources, the rules approach starts to fall short as the total number of possible words grows too large and problems such as including foreign languages cost you the entire effort all over again.</p>
<p align="justify">Instead we look to statistical solutions that help us deal with such large amounts of data. One such approach is naive Bayesian classification, which works by maintaining known classes of data (such as positive &amp; negative) and calculating the combined probability that an input falls into each one.</p>
<p align="justify">The statistical approach also means that the problems mentioned above start to matter much less. Spelling errors and grammatical mistakes become part of the set and have a weighting like any other word – and the same applies for foreign language words.</p>
<p align="justify">Of course, seeding the classes with quality data then becomes the problem, and the effectiveness of the statistical approach does very much depend on the quality of the data used to seed it.</p>
<p align="justify">Some studies have been done that used data from sources such a movie reviews, which was known to be good or bad through the star rating. Unfortunately, such sources are too specific to a particular domain and tend not to perform well enough for more general analysis.</p>
<p align="justify">One possible source for mass amounts of data is Twitter, but the problem then becomes a matter of categorising a set of tweets into positive or negative in order to seed the algorithm. A fairly simple way to produce the two sets of data is to assume that all tweets containing a <em>:) </em>are positive and that all tweets containing a <em>:( </em>are negative.</p>
<p align="justify">Though there would be countless exceptions in a large set of data, it doesn’t matter too much as it would only be a problem if there were enough exceptions to affect the probability significantly. </p>
<p align="justify">The approach described is <a href="http://brandlisten.com" target="_blank">in production</a> currently and producing good results. The set of seed data is fairly good with around 1 million tweets, but could be significantly bigger and consequently produce better results. </p>
<p align="justify">There are a number of real world applications of Bayesian classification that you’re probably already using, such as the spam filter. In addition, there are more sophisticated models that have been built on top of Bayesian classification and extend its application to fields like medicine. For further details, I recommend watching the <a href="http://scpro.streamuk.com/uk/player/Default.aspx?wid=7739" target="_blank">2010 Turing Lecture</a> which goes into great detail about this subject.</p>
<p align="justify">I’ve built a full demonstration application to show how it works in reality. The demo takes a sentence and performs a classification, showing how each word is analysed in the process. You can play around with the demonstration at <a href="http://sentiment.brandlisten.com" target="_blank">http://sentiment.brandlisten.com</a>.</p>
<p align="justify">If you feel like extending the algorithm, or you’re just curious to see how it works at a code level, you can find the code for the demo at <a href="https://github.com/martinrue/Sentan" target="_blank">https://github.com/martinrue/Sentan</a>.</p>
<p align="justify">And finally, here’s a link to the slides (which are mostly condensed versions of what has already been said here).</p>
<p align="justify"><a href="http://portal.sliderocket.com/AQJJH/Sentiment-Analysis" target="_blank">http://portal.sliderocket.com/AQJJH/Sentiment-Analysis</a></p>
]]></content:encoded>
			<wfw:commentRss>http://invalidcast.com/2011/04/sentiment-analysis-talk/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript &#8211; It&#8217;s Up Your Sleeve</title>
		<link>http://invalidcast.com/2011/04/javascript-its-up-your-sleeve/</link>
		<comments>http://invalidcast.com/2011/04/javascript-its-up-your-sleeve/#comments</comments>
		<pubDate>Tue, 12 Apr 2011 15:40:57 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://invalidcast.com/?p=413</guid>
		<description><![CDATA[This afternoon, JavaScript left me scratching my head due to an interesting fun little fact that I didn’t know. For full effect, picture the scene. I’m having a perfectly reasonable day, improved slightly by the amount of Tina Turner I had been listening to. I’m working on an application that captures interesting conversations from Twitter, [...]]]></description>
			<content:encoded><![CDATA[<p align="justify"><img style="background-image: none; border-right-width: 0px; margin: 0px 0px 0px 15px; padding-left: 0px; padding-right: 0px; display: inline; float: right; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" align="right" src="http://invalidcast.com/wp-content/uploads/2011/04/image.png" width="122" height="124" />This afternoon, JavaScript left me scratching my head due to an interesting fun little fact that I didn’t know. For full effect, picture the scene. </p>
<p align="justify">I’m having a perfectly reasonable day, improved slightly by the amount of Tina Turner I had been listening to. I’m working on an application that captures interesting conversations from Twitter, with the intention of seeding it with a great discussion between Uncle Bob and Dan North from last week.</p>
<p>  <span id="more-413"></span>
<p align="justify">The said conversation is withering away in Twitter’s archive and I’m hoping to complete this application swiftly before parts of the conversation become inaccessible to the API. I’m actually in the process of finishing the last bit that allows you to remove tweets from the final conversation.</p>
<p align="justify">In order to remove individual tweets, the full list is sent down to the client in an AJAX response. Each tweet is rendered in a <em>&lt;div&gt;</em> and has a new attribute that holds the tweet ID.</p>
<p align="justify">Let’s emulate the situation to demonstrate the problem:</p>
<pre class="brush: xml;">&lt;script type=&quot;text/javascript&quot;&gt;

    var data = { id: 487592080484679444 };

    function addAttribute() {
        $('#element').attr('id', data.id);
    }

&lt;/script&gt;

&lt;div id=&quot;element&quot;&gt;&lt;/div&gt;

&lt;a href=&quot;javascript:addAttribute()&quot;&gt;Add Attribute&lt;/a&gt;</pre>
<p align="justify">Starting from the top, we have an object called <em>data</em> which has a field called <em>id</em>. The value of <em>id</em> is the numeric ID of a tweet, which we’ll be adding to the &lt;div&gt;. The <em>addAttribute</em> method finds the <em>&lt;div&gt;</em> and sets the <em>id</em> attribute to the value from the object.</p>
<p align="justify">Let’s run it and see what happens. Before we click the link, the DOM looks like:</p>
<p align="justify"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="1" border="0" alt="1" src="http://invalidcast.com/wp-content/uploads/2011/04/1.png" width="485" height="244" /></p>
<p align="justify">As expected, we have our <em>&lt;div&gt;</em> and its <em>id</em> is still set to <em>‘element’</em>. Now let’s click the link and cause the <em>addAttribute </em>to run. Here’s the DOM afterwards:</p>
<p><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="2" border="0" alt="2" src="http://invalidcast.com/wp-content/uploads/2011/04/2.png" width="486" height="239" /></p>
<p align="justify">And there we go, our <em>id</em> is now set. But wait, what the hell &#8211; take another look at the value of the attribute and compare it to the value in the object. In pure JavaScript magic, it seems our original <em>id</em> of 487592080484679444 has been transformed into 487592080484679400.</p>
<p align="justify">While being wholly entertaining, and the very good trick not withstanding, I’d like to keep my hair for a few more years. After looking into the problem, it turns out that I was (until now) blissfully unaware that:</p>
<blockquote>
<p>All numbers in Javascript are 64bit (8 bytes) floating point numbers…</p>
<p>Integers are considered reliable (numbers without a period or exponent notation) to 15 digits (9e15). Floating point numbers are considered only as reliable as possible and no more!</p>
</blockquote>
<p>(<a href="http://www.hunlock.com/blogs/The_Complete_Javascript_Number_Reference" target="_blank">http://www.hunlock.com/blogs/The_Complete_Javascript_Number_Reference</a>)</p>
<p align="justify">Ah, 15 digits – that’s how it’s done. </p>
<p align="justify">Good one JavaScript, but not so impressive now that I know your dirty secret. Looks like it’s strings for this one.</p>
]]></content:encoded>
			<wfw:commentRss>http://invalidcast.com/2011/04/javascript-its-up-your-sleeve/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>ASP.NET &#8211; Thinking In Resources</title>
		<link>http://invalidcast.com/2011/03/asp-net-thinking-in-resources/</link>
		<comments>http://invalidcast.com/2011/03/asp-net-thinking-in-resources/#comments</comments>
		<pubDate>Fri, 11 Mar 2011 17:25:06 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://invalidcast.com/?p=397</guid>
		<description><![CDATA[A few months ago I wrote Tinyweb, an ASP.NET web framework which dictates an SRP approach to building web applications. Since then I’ve used Tinyweb for a few internal things and I’ve been happy with the direction it leads you in. So, we’ve all heard enough times by now the benefits of the SOLID principles. [...]]]></description>
			<content:encoded><![CDATA[<p align="justify">A few months ago I wrote <a href="https://github.com/martinrue/Tinyweb" target="_blank">Tinyweb</a>, an ASP.NET web framework which dictates an SRP approach to building web applications. Since then I’ve used Tinyweb for a few internal things and I’ve been happy with the direction it leads you in.</p>
<p align="justify"><img style="background-image: none; border-right-width: 0px; margin: 0px 0px 0px 10px; padding-left: 0px; padding-right: 0px; display: inline; float: right; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="SRP" border="0" alt="SRP" align="right" src="http://invalidcast.com/wp-content/uploads/2011/03/SingleResponsibilityPrinciple1.jpg" width="131" height="87" />So, we’ve all heard enough times by now the benefits of the SOLID principles. In particular, we know that we should minimise the responsibility of a class, with the aim of having just one responsibility per class and consequently only one reason for that class to change.</p>
<p align="justify">That’s an interesting word – change. We often refer to new work on an existing system as change, but unless the new work involves modifying the way something worked before, it shouldn’t be change, it should be extension. </p>
<p align="justify">As you know, another SOLID principle tells us that code should be open for extension, but closed for modification. Usually this refers to being able to extend behaviour by subclassing and using polymorphism to effectively replace the old behaviour – but can’t OCP be more generally applied?</p>
<p align="justify">What about our architecture, project layout, working conventions? Have these been arranged to support extension or will a change require that we have to rethink these things in order to accommodate future changes?</p>
<p>  <span id="more-397"></span>
<p><strong>How Tinyweb Helps</strong></p>
<p align="justify">Tinyweb takes a rest-style approach to building web applications by enforcing that a handler can only handle the standard HTTP methods for a single URL. For example, if we have a <em>UsersHandler</em> (liken this to a controller in MSMVC parlance) we will have a <em>/Users </em>URL and will only be able to respond to the HTTP GET, POST, PUT and DELETE methods for this resource.</p>
<p align="justify">Where in MSMVC you might have an <em>AccountController</em> with all kinds of actions, Tinyweb dictates that every URL is a separate resource independent of all others and requires its own handler.</p>
<p align="justify">I think this helps in enforcing a certain level of granularity and responsibility. While you can’t really argue that a handler has single responsibility (since it might handle both GET and POST), it more broadly has the single responsibility of controlling interactions with that resource.</p>
<p align="justify">This is why the web has evolved so successfully – everything is ultimately just an addressable resource that can send you to other resources in some coherent way to achieve a goal. Adding new functionality simply involves deciding which new resource to introduce and deciding how it will integrate with the existing system.</p>
<p><strong>User Signup Example</strong></p>
<p align="justify">Let’s see this workflow in action by using a simple example. Let’s pretend we’re building some web based system that requires users to sign up for accounts. We’ll start with a generic user registration system.</p>
<pre class="brush: csharp;">public class UserRegisterHandler
{
    public IResult Get()
    {
        return View.Spark(&quot;Signup.spark&quot;);
    }
}</pre>
<p align="justify">By creating a handler named <em>UserRegisterHandler</em>, I’m in effect creating a resource addressable at <em>/User/Register</em> which can support any of the standard HTTP methods. In this particular case, I’ve implemented the HTTP GET method to allow the resource to display a view for a potential user to submit their account details.</p>
<p align="justify">
<p align="justify">Still thinking in terms of resources, we should now consider which resource will handle receiving a user’s details and creating the account. For the purposes of this example, we’ll use the same resource. So, a GET request to <em>/User/Register</em> will get the user registration view and a POST request to <em>/User/Register</em> will create the user.</p>
<pre class="brush: csharp;">public class UserRegisterHandler
{
    IAccountService _accountService;

    public UserRegisterHandler(IAccountService accountService)
    {
        _accountService = accountService;
    } 

    public IResult Get()
    {
        return View.Spark(&quot;Signup.spark&quot;);
    } 

    public IResult Post(User user)
    {
        _accountService.Create(user);
        return Result.String(&quot;Done&quot;);
    }
}</pre>
<p align="justify">I’ve made a couple of changes to the handler here. I’ve introduced a dependency on an IAccountService which will handle the user registration. I’ve also implemented the HTTP POST method which binds the POST data to a User object and passes that down to the account service to do its magic.</p>
<p align="justify">Let’s continue this pretentious silliness and imagine that we’ve just been informed of our next requirement. Apparently, our current handling of new users leaves a lot to be desired. We’ve been told that when new users sign up, they should be taken to a page that welcomes them and confirms their details.</p>
<p align="justify">Because we’re thinking exclusively in terms of the resources our system is composed of, the next question becomes: which resource do we need to introduce to support this extension? </p>
<p align="justify">We’ll create a <em>UserWelcomeHandler</em>, giving us a new resource addressable at /User/Welcome. Let’s assume that a client will pass us the ID of the user we’re welcoming when issuing a GET request to this resource.</p>
<pre class="brush: csharp;">public class UserWelcomeHandler
{
    IAccountService _accountService;

    public UserWelcomeHandler(IAccountService accountService)
    {
        _accountService = accountService;
    }

    public IResult Get(int id)
    {
        var model = _accountService.GetWelcomeDetails(id);
        return View.Spark(model, &quot;Welcome.spark&quot;);
    }
}</pre>
<p align="justify">The user ID is now being taken from the GET request and being passed to the account service to fetch a model that represents the welcome details for that user. The model can then be rendered to a view as normal.</p>
<p align="justify">The new requirement has been implemented by introducing a new resource and extending the original system. But there’s still a missing link between the two resources, and we’ll have to return to the <em>UserRegisterHandler</em> and modify it. Instead of just displaying “done”, we want it to delegate responsibility to our new <em>/User/Welcome</em> resource.</p>
<pre class="brush: csharp;">public class UserRegisterHandler
{
    IAccountService _accountService;

    public UserRegisterHandler(IAccountService accountService)
    {
        _accountService = accountService;
    } 

    public IResult Get()
    {
        return View.Spark(&quot;Signup.spark&quot;);
    } 

    public IResult Post(User user)
    {
        var userID = _accountService.Create(user);

        var url = Url.For&lt;UserWelcomeHandler&gt;(new { UserID = userID });
        return Result.Redirect(url);
    }
}</pre>
<p align="justify">With this change, the responsibility of <em>UserRegisterHandler</em> has been contained to dealing with the new account creation only. Satisfying our new requirement of welcoming the user has been implemented by introducing a new resource. We now simply move between the separate resources as required.</p>
<p align="justify"><strong>The Point</strong></p>
<p align="justify">Although you could easily work this way with any framework, <a href="https://github.com/martinrue/Tinyweb" target="_blank">Tinyweb</a> makes it more explicit with its opinionated approach to what a handler can do. You’re forced to think about separate resources and how they should collaborate to form a coherent system – and ultimately, this feels like a very natural and intentional way to build applications.</p>
]]></content:encoded>
			<wfw:commentRss>http://invalidcast.com/2011/03/asp-net-thinking-in-resources/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Tinyweb Does Mono</title>
		<link>http://invalidcast.com/2011/01/tinyweb-does-mono/</link>
		<comments>http://invalidcast.com/2011/01/tinyweb-does-mono/#comments</comments>
		<pubDate>Sat, 01 Jan 2011 17:24:54 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://invalidcast.com/?p=339</guid>
		<description><![CDATA[For a long time, the Microsoft technology stack was pretty much glued to Windows. If you wanted to use Microsoft technology, you&#8217;d pretty much need to use compilers, runtimes and servers that existed only for Windows. Back then, the closest thing we had to cross-platform were things like WINE which simply tried to emulate the [...]]]></description>
			<content:encoded><![CDATA[<p align="justify"><img style="background-image: none; border-right-width: 0px; margin: 0px 0px 0px 5px; padding-left: 0px; padding-right: 0px; display: inline; float: right; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="" border="0" alt="mono logo" align="right" src="http://invalidcast.com/wp-content/uploads/2011/01/mono-logo.gif" width="101" height="114" />For a long time, the Microsoft technology stack was pretty much glued to Windows. If you wanted to use Microsoft technology, you&#8217;d pretty much need to use compilers, runtimes and servers that existed only for Windows. Back then, the closest thing we had to cross-platform were things like WINE which simply tried to emulate the entire runtime environment.</p>
<p align="justify">Times have certainly changed, particularly when it comes to web development. Thanks to awesome projects like Mono, it&#8217;s no longer the case that working with C# / ASP.NET binds you to Microsoft development tools and forces you to use Windows for development and hosting.</p>
<p align="justify">Mono brings a C# compiler and CLI implementation (in addition to other things) to operating systems such as Linux and Mac OS X, making technologies like C# and ASP.NET much more feasible and available.</p>
<p>    <span id="more-339"></span>
<p align="justify">Let&#8217;s see how easy it is to get up and running on Mac OS X using things we&#8217;d normally only assume were doable using Visual Studio and Windows. We’ll create a C# ASP.NET application using Mono and MonoDevelop (the IDE). We could also use ASP.NET MVC, but to further demonstrate how easy cross-platform has become with Mono, we&#8217;ll use a lightweight web framework that I have been working on called <a href="https://github.com/martinrue/Tinyweb" target="_blank">Tinyweb</a>. And while we&#8217;re at it, let&#8217;s add the Spark view engine and StructureMap to the mix too.</p>
<p align="justify">The first thing you’ll need to do is install Mono and MonoDevelop. Head over to <a href="http://www.go-mono.com/mono-downloads/download.html" target="_blank">http://www.go-mono.com/mono-downloads/download.html</a> and <a href="http://monodevelop.com/download" target="_blank">http://monodevelop.com/download</a> and install the packages for your version of OS X. If you’re following this using Linux instead, just install the Linux packages and everything else should work in the same way.</p>
<p align="justify">Here’s one I prepared earlier:</p>
<p align="justify"><a href="http://invalidcast.com/wp-content/uploads/2011/01/3.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2011/01/3_thumb.png" width="545" height="409" /></a></p>
<p align="justify">MonoDevelop provides much the same experience that Visual Studio provides, so you should be pretty familiar with how it works, even if you’ve never used it before. The next job is to create a new solution, which is done exactly how you might expect: File –&gt; New –&gt; Solution.</p>
<p align="justify">Here’s another one I prepared earlier:</p>
<p align="justify"><a href="http://invalidcast.com/wp-content/uploads/2011/01/4.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2011/01/4_thumb.png" width="521" height="408" /></a></p>
<p align="justify">After entering the name and location, you should have a new solution with an empty ASP.NET project. Since we’re using Tinyweb as our web framework, the next thing we need to do is add the Tinyweb assemblies to the project.</p>
<p align="justify">You can get Tinyweb from its <a href="https://github.com/martinrue/Tinyweb" target="_blank">github repository</a> and compile it yourself, but to make life easier there’s also a <a href="http://ci.thunder.invalidcast.com" target="_blank">continuous release build here</a>. You don’t need an account to access the CI server, just click the <em>Login as a Guest User</em> link at the bottom:</p>
<p align="justify"><a href="http://invalidcast.com/wp-content/uploads/2011/01/1.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2011/01/1_thumb.png" width="584" height="431" /></a></p>
<p align="justify">Once you have logged in, you should see the latest build of Tinyweb and a link to the build artifacts. Download the <em>Tinyweb.zip</em> archive which contains the various assemblies you’ll need to work with Tinyweb.</p>
<p align="justify"><a href="http://invalidcast.com/wp-content/uploads/2011/01/2.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2011/01/2_thumb.png" width="599" height="230" /></a></p>
<p align="justify">As an interesting side-point, the TeamCity server is actually a Windows Server 2008 machine building the Tinyweb project directly from its github repository using MSBuild, and yet we’re able to download these same assemblies and use them on a completely different operating system.</p>
<p align="justify">Let’s add references to the assemblies we’ll need. You’ll notice that the archive is organised into two directories: <em>Framework </em>and <em>View Engines</em>. You need to add references to both assemblies from <em>Framework</em>, and both assemblies from <em>View Engines/Spark:</em></p>
<p><a href="http://invalidcast.com/wp-content/uploads/2011/01/5.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2011/01/5_thumb.png" width="596" height="447" /></a></p>
<p align="justify">To keep things simple, we’ll create an application which handles requests for the URL <em>/home</em>. In Tinyweb land, this is a simple matter of creating a <em>HomeHandler</em> class and adding the required method to reflect the type of request we want to handle:</p>
<p><a href="http://invalidcast.com/wp-content/uploads/2011/01/6.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2011/01/6_thumb.png" width="594" height="376" /></a></p>
<p align="justify">Tinyweb uses a convention whereby the name of the handler (excluding the word handler) is used as the URL that the handler responds to. It’s possible to override this convention by declaring a Route field in the class, like this:</p>
<pre class="brush: csharp;">public class HomeHandler
{
    Route route = new Route(&quot;UnconventionalUrl&quot;);

    public IHandlerResult Get()
    {
        return Result.String(&quot;Hello World&quot;);
    }
}</pre>
<p align="justify">The handler would now respond to requests for the URL <em>/UnconventionalUrl, </em>not its original URL of <em>/home</em>.</p>
<p align="justify">Looking at our code so far, you’ll notice that we have a public method named <em>Get</em>. Methods in Tinyweb handlers must be named to match one of the HTTP verbs that they intend to process. Currently, we’ll be processing HTTP GET requests and returning a raw string as output.</p>
<p align="justify">So, we have a solution, we have a project, we have references to Tinyweb and we have a handler. Next up we need to initialise the Tinyweb framework at application start-up, cue Global.asax:</p>
<p align="justify"><a href="http://invalidcast.com/wp-content/uploads/2011/01/8.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2011/01/8_thumb.png" width="600" height="330" /></a></p>
<p align="justify">Nothing too ground-breaking here. We’ve just added a Global.asax file so we can hook into the ASP.NET application start-up event and call <em>Tinyweb.Init</em>. The <em>Tinyweb.Init </em>call simply provokes the framework to scan for <em>handlers</em> and set up the routes that have been found.</p>
<p align="justify">The last remaining thing to do is to make sure we’re targeting .NET 4 (because Tinyweb is compiled against version 4 of the CLR). Simply right-click the project and select properties. If any rocket scientists are reading, I apologise:</p>
<p><a href="http://invalidcast.com/wp-content/uploads/2011/01/7.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2011/01/7_thumb.png" width="598" height="396" /></a></p>
<p align="justify">With any luck, you should now be able to build the solution and run it. When you run the project, MonoDevelop will start a local instance of the XSP web server on port 8080 in much the same way that Visual Studio uses its own local development server:</p>
<p><a href="http://invalidcast.com/wp-content/uploads/2011/01/9.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2011/01/9_thumb.png" width="606" height="369" /></a></p>
<p align="justify">That was a pleasant experience, let’s continue with the demo and see how we can bring Spark to the party. In terms of code, we only need to make a slight change in order to return a Spark view instead of the raw string currently being returned:</p>
<p><a href="http://invalidcast.com/wp-content/uploads/2011/01/10.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2011/01/10_thumb.png" width="608" height="335" /></a></p>
<p align="justify">The <em>return</em> statement has been changed to point to the Spark view file <em>Hello.spark</em>. Let’s see what happens when we run the project again:</p>
<p><a href="http://invalidcast.com/wp-content/uploads/2011/01/11.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2011/01/11_thumb.png" width="610" height="356" /></a></p>
<p align="justify">Good, that’s what we should have expected since we’ve not created the view file yet. Easy fix – let’s create the view file <em>Hello.spark</em> in the root of the project:</p>
<p><a href="http://invalidcast.com/wp-content/uploads/2011/01/12.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2011/01/12_thumb.png" width="606" height="336" /></a></p>
<p align="justify">It’s not a particularly ambitious view, we’re just keeping with the <em>hello world</em> theme while also using the Spark encoded output syntax <em>${}</em> to output the current date and time from <em>System.DateTime.Now</em>. And, for my final trick:</p>
<p><a href="http://invalidcast.com/wp-content/uploads/2011/01/13.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2011/01/13_thumb.png" width="482" height="245" /></a></p>
<p align="justify">If you were wondering what happened to StructureMap – it’s actually a dependency of Tinyweb and used internally when a handler needs instantiating to handle a request. If you were to add a constructor-injected dependency to a handler, you’d just need to supply a StructureMap registry to the <em>Tinyweb.Init</em> call in order to have that dependency supplied at runtime.</p>
<p align="justify">So there you have it – C#, ASP.NET, Tinyweb, Spark and StructureMap coming to you from sunny OS X, thanks to Mono.</p>
<p align="justify"><strong>EDIT</strong></p>
<p align="justify">Due to the use of images in this post, the code samples have not been updated to reflect the latest public API changes in Tinyweb v2.0.0. The only significant difference is the renaming of <strong>IHandlerResult</strong> to <strong>IResult</strong>, so please be aware of this when following along.</p>
]]></content:encoded>
			<wfw:commentRss>http://invalidcast.com/2011/01/tinyweb-does-mono/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>How Hard Could It Be?</title>
		<link>http://invalidcast.com/2010/12/how-hard-could-it-be/</link>
		<comments>http://invalidcast.com/2010/12/how-hard-could-it-be/#comments</comments>
		<pubDate>Mon, 20 Dec 2010 18:37:37 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Projects]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://invalidcast.com/?p=305</guid>
		<description><![CDATA[Like most programmers, I spend a portion of my free time working on side projects. Lots of programmers I know do this. Some hope they’ll strike oil one day in terms of commercial success, but most do it because I code, therefore I am, and it’s a good way to keep learning and improving. From [...]]]></description>
			<content:encoded><![CDATA[<p align="justify"><img style="background-image: none; border-right-width: 0px; margin: 0px 0px 0px 3px; padding-left: 0px; padding-right: 0px; display: inline; float: right; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="" border="0" alt="" align="right" src="http://invalidcast.com/wp-content/uploads/2010/12/image7.png" width="150" height="185" />Like most programmers, I spend a portion of my free time working on <em>side projects</em>. Lots of programmers I know do this. Some hope they’ll strike oil one day in terms of commercial success, but most do it because <em>I code, therefore I am, </em>and it’s a good way to keep learning and improving.</p>
<p align="justify">From my very early days as a programmer, I would only be interested in very ambitious projects. It all started when I thought <a href="http://e-asm.org" target="_blank">writing a compiler</a> couldn’t exactly be rocket science, but of course, I hadn’t factored in the <em>badly</em>. Turns out rocket science is easy. But that was nothing compared to the firewall I tried to write (to be fair, I did actually get it working for defined packet filter rules. Please stop clapping). And let’s just not mention the protected mode kernel in x86 assembly. </p>
<p>  <span id="more-305"></span>
<p align="justify">Back then, and even now, people often say things like <em>why bother?</em> or <em>but there’s already this other thing. </em>To me, these are just challenges. I’m not trying to change the world and I won’t lose more than 3 nights of sleep if nobody ever uses what I’m working on. 4 at the most.</p>
<p align="justify">The point of a side project (if not commercial) is to push yourself out of your comfort zone – sometimes drastically. Doing this forces you to learn a ton. Learning how to write a compiler probably doesn’t transfer the most relevant knowledge, but generally speaking, ambitious projects provide lots of learning opportunity that you don’t tend to find in smaller projects, and I suspect this is why I am addicted to them.</p>
<p align="justify"><strong>Tinyweb</strong></p>
<p align="justify">Earlier this week I released <a href="https://github.com/martinrue/Tinyweb" target="_blank">Tinyweb</a> – a simple web framework for asp.net. While a web framework sitting on top of asp.net isn’t particularly ambitious, it was something I had little knowledge of. Pushing myself out of my comfort zone definitely taught me a lot and I’ll be writing some more about Tinyweb in another post.</p>
<p align="justify"><strong>Mide</strong></p>
<p align="justify">Before questioning how hard a web framework could possibly be, I did briefly wonder how hard Visual Studio itself could be to write. And that brief moment was all it took. Apparently I have too much free time on my hands.</p>
<p align="justify">Well, let me tell you, the answer is hard. Luckily, I set my goals a <strike>little</strike> lot below those of Visual Studio. I figured having a simple text editor that could provide some of the core features of Visual Studio in terms of solution management and compilation/publishing would be great for situations where you don’t have VS (crazy idea, I know), or you want to quickly write a throw-away experiment.</p>
<p align="justify">So the result is Mide (Mini IDE).</p>
<p align="justify"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2010/12/image1.png" width="595" height="295" /></p>
<p align="justify">Before a solution is opened, Mide acts like a normal text editor – letting you edit and save individual files. Once you open a solution, Mide shows you the familiar tree structure you see in VS:</p>
<p><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2010/12/image2.png" width="592" height="313" /></p>
<p align="justify">For the most part, Mide offers the same control over the solution tree. Files, folders, references and projects can be added and removed from the solution. Mide is exclusively keyboard driven, so all such actions can only be performed through their associated keyboard shortcut (see shortcuts.txt in archive).</p>
<p align="justify">Mide still doesn’t implement some key things, such as execution of a test runner for unit test projects or the creation of new solutions from scratch (the File –&gt; New Solution menu option doesn’t work yet). However, if you have an existing solution that you quickly need to edit, Mide should be able to handle that.</p>
<p align="justify">Mide can also be configured (though Build –&gt; Settings…) to build and publish projects. This means that you can run builds as you’re writing code, and then publish directly to an IIS instance for testing your application locally. However, there’s no debugger or IntelliSense – <a href="http://www.sadtrombone.com" target="_blank">sad trombone</a>.</p>
<p align="justify">You can download an archive containing Mide <a href="http://invalidcast.com/wp-content/uploads/Mide.zip">here</a>, please feel free to leave feedback. Note: Mide rewrites your .csproj and .sln files as changes are made to the solution tree, so it’d be wise to backup any solutions before opening them in Mide – just in case.</p>
]]></content:encoded>
			<wfw:commentRss>http://invalidcast.com/2010/12/how-hard-could-it-be/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>My New Black</title>
		<link>http://invalidcast.com/2010/12/my-new-black/</link>
		<comments>http://invalidcast.com/2010/12/my-new-black/#comments</comments>
		<pubDate>Sun, 12 Dec 2010 23:25:23 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Projects]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://invalidcast.com/?p=295</guid>
		<description><![CDATA[A few days ago, I was minding my own business, writing some bad code, when this tweet caught my attention: It made me laugh, actually. In a guilty kind of way. Rob nailed it, it’s true, and you know how I know? Because that bad code I was writing was kind of pretty much exactly [...]]]></description>
			<content:encoded><![CDATA[<p align="justify"><img style="background-image: none; border-right-width: 0px; margin: 0px 0px 0px 10px; padding-left: 0px; padding-right: 0px; display: inline; float: right; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="New Black" border="0" alt="New Black" align="right" src="http://invalidcast.com/wp-content/uploads/2010/12/Betty_Boop1.jpg" width="122" height="215" />A few days ago, I was minding my own business, writing some bad code, when this tweet caught my attention:</p>
<p align="justify"><img style="background-image: none; border-right-width: 0px; margin: 5px 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="a .NET Sinatra clone in the new black" border="0" alt="a .NET Sinatra clone in the new black" src="http://invalidcast.com/wp-content/uploads/2010/12/image.png" width="323" height="89" /></p>
<p align="justify">It made me laugh, actually. In a guilty kind of way. Rob nailed it, it’s true, and you know how I know? Because that bad code I was writing was <strike>kind of</strike> pretty much exactly my new black.</p>
<p align="justify">I wouldn’t argue that we <strong>need</strong> another web framework, but I would say that a web framework is a cool project to undertake to learn more about how these things work (and how to write them badly).</p>
<p>  <span id="more-295"></span>
<p align="justify">In the spirit of hacking, I figured I’d try and write a simple web framework that sits on top of all the goodness of ASP.NET. Not having to worry about dealing with the underlying HTTP fundamentals and also having ASP.NET Routing at my disposal, it seemed like a fun thing to do.</p>
<p align="justify">I’m writing about it here in case others are thinking of experimenting in a similar fashion, perhaps it may serve as motivation – if I can do it, trust me, you can do it better.</p>
<p><strong>Tinyweb</strong></p>
<p align="justify">So, with the single goal of making it as easy as possible to use, I have come up with <a href="https://github.com/martinrue/Tinyweb" target="_blank">Tinyweb</a> (although, I can’t help but think that <em>Black</em> would have been a cooler name). And you know the cool thing about making your own framework? You can decide to do it how ever the hell you like, for instance:</p>
<p align="justify">To support dependency injection in the simplest way possible, the Tinyweb initialisation call optionally accepts an instance of a <em>StructureMap</em> registry and does the rest itself. Tinyweb also uses Spark for rendering views. Basically, it’s a little opinionated.</p>
<p align="justify">That said, you can still create a new <strong>IResult</strong> to render views using some other view engine, or supply your own version of the <strong>HandlerFactory</strong> to use another IOC container. Tinyweb hasn’t been locked into one specific way, it’s just <em>my sensible</em> default.</p>
<p><strong>So, how does it work?</strong></p>
<p align="justify">The workflow is as simple as I could think to make it. It’s important you understand that this means it could probably be much simpler. Here are the steps for creating a web app using Tinyweb:</p>
<ul>
<li>
<div align="justify">Create a <strong>public class</strong> <em>WhateverYouLikeHere</em><strong>Handler </strong>with method(s) that match the name of the HTTP verb they respond to. For example, your <strong>SignupHandler</strong> might have a <strong>Get</strong> method that renders a view for user signup and a <strong>Post</strong> method that accepts the user registration data after the form is posted. </div>
</li>
<li>
<div align="justify">Make a call to <strong>Tinyweb.Init</strong> from <strong>Application_Start</strong> </div>
</li>
</ul>
<p align="justify">And, that’s it.</p>
<p><strong>What about routes?</strong></p>
<p align="justify">Oh yeah, routes. Routes are determined through the class name too. In the example above, the route to the handler is /<em>Whatever/You/Like/Here. </em>If I innocently created a <strong>RickRollHandler</strong>, it would be automatically configured to respond to the URL /Rick/Roll.</p>
<p align="justify">This is just a convention and can be modified by the creation of a <strong>Route</strong> field. If I want my <strong>RickRollHandler</strong> to be much more successful, I might do the following:</p>
<pre class="brush: csharp;">public class RickRollHandler
{
    Route route = new Route(&quot;Images/AnnaKournikova&quot;);

    public IResult Get()
    {
        return Result.Html(&quot;Muahahahah.html&quot;);
    }
}</pre>
<p><strong>Framework Design</strong></p>
<p align="justify">Once Tinyweb has be initialised, it is aware of all URLs that the application serves and the type of handler that should be created for each one. Here’s what happens when some honest, innocent guy tries to request our image of Anna Kournikova:</p>
<ul>
<li>
<div align="justify">An <strong>IHandlerFactory</strong> is used to create an instance of the handler that has been associated with the URL being requested. If you haven’t set your own <strong>HandlerFactory</strong>, don’t panic, the <strong>DefaultHandlerFactory</strong> will be used – which uses Structure Map to create the handler. If you supplied a <strong>Registry</strong> to the <strong>Tinyweb.Init</strong> call, this could mean that the creation of the handler also involves the creation of any dependencies.</div>
</li>
<li>
<div align="justify">An <strong>IHandlerInvoker</strong> is then used to call the correct method on the handler. If the request was an HTTP GET, the <strong>DefaultHandlerInvoker</strong> would be looking for a method called Get. The same goes for POST, PUT and DELETE. And again, if this makes you reach for the little foam stress duck on your desk with a panic of hand crunches, fear not, you can always create your own <strong>MyBatshitCrazyHandlerInvoker: IHandlerInvoker</strong> that uses star signs to call the right method.</div>
</li>
<li>
<div align="justify">Lastly, the method being called on the handler must return an <strong>IResult</strong> back to the <strong>IHandlerInvoker</strong>. The <strong>IResult</strong> essentially just describes a class that must have a <strong>ProcessResult</strong> method, and some other dull things. Once the <strong>IResult</strong> is returned, the <strong>ProcessResult</strong> method is called to obtain the response, and naturally, this is then put on the response stream and sent back to the honest, innocent guy looking for naked pictures of women on the internet. </div>
</li>
</ul>
<p align="justify">The only other bit is the scanning of handlers, which is performed during the <strong>Tinyweb.Init</strong> call. Handlers are those classes that end with the word <em>Handler</em> and have at least one method that corresponds to one of the four HTTP verbs.</p>
<p align="justify">Handlers are found by asking the current <strong>IHandlerScanner </strong>for them. You may be able to guess what I’m about to say next. If you want to customise (more likely optimise) the way that handlers are found, just create your own <strong>MyBatshitCrazyHandlerScanner</strong> and ask Tinyweb to use that instead. Despite the insanity of such a thing, it will oblige.</p>
<p align="justify"><strong>OK, I’m Interested</strong></p>
<p align="justify">Together with the framework there are a couple of example applications demonstrating things like Spark view rendering and model binding. Feel free to <a href="https://github.com/martinrue/Tinyweb" target="_blank">browse around the project</a> and I’d be happy to hear feedback.</p>
<p>There’s no binary release, as I expect the 2 people who care about this have VS2010/.NET4 and can compile it themselves, but if anyone wants to check it out and can’t, let me know and I’ll get a binary version up there too.</p>
<p><strong>EDIT</strong></p>
<p>There is now a binary release, so if you don’t want to compile it yourself you can pull down the latest build from the <a href="http://ci.thunder.invalidcast.com" target="_blank">build server</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://invalidcast.com/2010/12/my-new-black/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Agile Conversations</title>
		<link>http://invalidcast.com/2010/11/agile-conversations/</link>
		<comments>http://invalidcast.com/2010/11/agile-conversations/#comments</comments>
		<pubDate>Sun, 07 Nov 2010 15:58:45 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Observations]]></category>

		<guid isPermaLink="false">http://invalidcast.com/?p=284</guid>
		<description><![CDATA[How many times have you been in a debate that quickly turned into an argument, completely losing focus of the original point? How many times have you been on the receiving end of a sneering told you so? How about simply being laughed at for being wrong about something? As children, we grow up believing [...]]]></description>
			<content:encoded><![CDATA[<p align="justify"><img style="background-image: none; border-right-width: 0px; margin: 0px 0px 0px 15px; padding-left: 0px; padding-right: 0px; display: inline; float: right; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="" border="0" alt="" align="right" src="http://invalidcast.com/wp-content/uploads/2010/11/conversation1.gif" width="144" height="112" />How many times have you been in a debate that quickly turned into an argument, completely losing focus of the original point? How many times have you been on the receiving end of a sneering <em>told you so</em>? How about simply being laughed at for being wrong about something?</p>
<p align="justify">As children, we grow up believing that we should be right and that being wrong is a bad thing. If we are wrong, the other kids will laugh at us. If we are right, the other kids will think we&#8217;re smart and respect us (until the degree of <em>geek</em> – but that’s a whole other post). Pride and confidence become tangled up in a complex web, woven by the <em>I could be wrong again</em> spider.</p>
<p>  <span id="more-284"></span>
<p align="justify">For most of us, this isn&#8217;t something we grow out of. In fact, it gets worse. As adults we are expected to be right more often, and so it seems much worse to be wrong. This mindset quickly becomes prohibitive of doing anything that involves any risk of failure. We&#8217;ll stay on the fence of debates, we&#8217;ll only do things we have already done and we&#8217;ll only do new things in private or if there&#8217;s a low risk of failure. </p>
<p align="justify">I&#8217;ve wrote about this subject before when I asked <a href="http://invalidcast.com/2009/08/are-you-failing-enough" target="_blank">Are You Failing Enough?</a> and suggested that people learn just as much from failure as they do from success. Yet, sadly most people will avoid failure so relentlessly that they won&#8217;t do anything that could result in it.</p>
<p align="justify">We need to get out of the habit of caring who is right and who is wrong in a conversation. It really doesn&#8217;t matter. What matters is the learning and understanding coming from the conversation itself. Care about what you get out of the conversation.</p>
<p align="justify">If someone corrects you, they have taken their own time to ensure that you have grown in some way. They have invested their time into you and now you have that knowledge too. On the other hand, if you learn nothing from the conversations you engage in, you&#8217;re not growing nearly as much (and this is most likely because you&#8217;re not in the right mind to learn anything new, not necessarily because no one is able teach you something).</p>
<p align="justify">Accepting that you&#8217;re wrong or allowing someone to impart some knowledge is not a form of weakness, it&#8217;s very much the opposite. The one who grows from every conversation and improves by absorbing knowledge and wisdom from those around her is strong, and most able to grow stronger in the future. The one who argues the irrelevant points to gain some form of conversational victory is the weak one, and they&#8217;re missing the entire point of conversing in the first place.</p>
<p align="justify">When people take advantage of this, conversation is remarkably refreshing. For me, it’s just as refreshing as when I first discovered the agile method of software development. Put this into conversational terms and it kind of makes sense.</p>
<p align="justify">In a waterfall conversation, people try to be right upfront and aren’t typically adaptive if their opinions or understanding should be changed through being wrong. In a waterfall conversation, ideally, things said at the beginning of the conversation remain unchanged by the end.</p>
<p align="justify">In an agile conversation, people feel free to contribute ideas that could be wrong – using the fact that they’re wrong to drive the direction of the conversation and learn more about what they are discussing. An agile conversation iterates and people learn just as with software development.</p>
<p align="justify">Ultimately, the nature of a good debate is that people will disagree, but unless people want to listen and adjust their understanding (be agile in conversation), nothing will be learnt and we will just mindlessly argue.</p>
<p align="justify">Use the fact that you could be wrong as a tool for learning. Don’t worry about being right or being wrong, just focus on iterating the conversation and exchanging knowledge. In the end, if you end up being right about something, great – you have verified some knowledge. But more importantly, if you end up being wrong about something, even better – you have just learnt something, <strong>and that is the point.</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://invalidcast.com/2010/11/agile-conversations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Funcy Testing</title>
		<link>http://invalidcast.com/2010/10/funcy-testing/</link>
		<comments>http://invalidcast.com/2010/10/funcy-testing/#comments</comments>
		<pubDate>Fri, 29 Oct 2010 17:55:00 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://new.invalidcast.com/2010/10/funcy-testing/</guid>
		<description><![CDATA[Testing in ASP.NET is often said to be harder than it should be. Usually we end up creating wrappers around dependencies such as Url, File and DateTime that allow us to mock them within our tests (and I don’t mean laugh at them). But, as Harry Pierson recently pointed out, following this practice for every [...]]]></description>
			<content:encoded><![CDATA[<p align="justify">Testing in ASP.NET is often said to be harder than it should be. Usually we end up creating wrappers around dependencies such as <em>Url</em>, <em>File</em> and<em> DateTime</em> that allow us to mock them within our tests (and I don’t mean laugh at them). But, as <a href="http://devhawk.net/default.aspx" target="_blank">Harry Pierson</a> recently <a href="http://devhawk.net/2010/10/08/Testing+The+Untestable+With+Delegate+Injection.aspx" target="_blank">pointed out</a>, following this practice for every dependency can often lead to a huge constructor and pretty ugly code.</p>
<p><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="" border="0" alt="Extreme Programming" src="http://invalidcast.com/wp-content/uploads/2010/10/11.gif" width="477" height="277" /></p>
<p>  <span id="more-123"></span>
<p align="justify">Rather than the typical approach of creating and injecting a new mockable dependency, Harry’s example uses a <em>public Func&lt;&gt; / Action&lt;&gt;</em> on the controller that encapsulates the dependency and allows it to be overridden simply by assigning it a new delegate.</p>
<p align="justify">So, fast forward a few days I’m writing a test for the BugController’s DeleteBug method:</p>
<pre class="brush: csharp;">[HttpPost]
public ActionResult DeleteBug(int bugID)
{
    try
    {
        bugService.Delete(bugID);

        return Json(new
        {
            Succeeded = true,
            RedirectUrl = Url.Action(&quot;bugs&quot;, &quot;project&quot;)
        });
    }
    catch (ModelValidationException exception)
    {
        return Json(exception.Description);
    }
}</pre>
<p align="justify">
<p>Regardless of success or failure, the controller should return a JsonResult when deleting a bug. Seems like a straightforward test – let’s just make sure a JsonResult is always returned from the action:</p>
<pre class="brush: csharp;">[Test]
public void DeleteBug_WithValidBugID_ReturnsJsonResult()
{
    var bugService = new Mock&lt;IBugService&gt;();
    var controller = new BugController(bugService.Object); 

    var result = controller.DeleteBug(1); 

    Assert.IsInstanceOf&lt;JsonResult&gt;(result);
}</pre>
<p align="justify">
<p>If only it was that simple.</p>
<pre>Failed: System.NullReferenceException :
Object reference not set to an instance of an object.</pre>
<p align="justify">The test is failing because of the dependency on <em>Url.Action</em>. When running under ASP.NET the controller is supplied with an instance, but during test it is null. In this particular case, the test doesn’t really care about what <em>Url.Action</em> is doing – we just need to prevent it from breaking the test.</p>
<p align="justify">So, rather than creating a wrapper around <em>Url.Action</em> and then injecting &amp; mocking it, let’s see how <a href="http://devhawk.net/2010/10/08/Testing+The+Untestable+With+Delegate+Injection.aspx" target="_blank">Harry’s approach</a> works. First we’re going to create a <em>public Func&lt;&gt;</em> to hold a delegate that will replace the dependency.</p>
<pre class="brush: csharp;">public class BugsController : Controller
{
    public Func&lt;string, string, object, string&gt; @UrlAction;

    ...
}</pre>
<p align="justify">The reason for the somewhat redundant @ prefix is just to show the intent of this declaration more clearly. At a glance we can see that this is for testing and distinguish it from whatever else might be declared here.</p>
<p align="justify">Next, we need to modify the implementation slightly so that it uses the delegate instead of being coupled to <em>Url.Action</em>.</p>
<pre class="brush: csharp;">[HttpPost]
public ActionResult DeleteBug(int bugID)
{
    try
    {
        bugService.Delete(bugID);

        return Json(new
        {
            Succeeded = true,
            RedirectUrl = @UrlAction(&quot;bugs&quot;, &quot;project&quot;, null)
        });
    }
    catch (ModelValidationException exception)
    {
        return Json(exception.Description);
    }
}</pre>
<p align="justify">
<p>Almost there. We now need to ensure that the delegate gets a default instance that uses the original <em>Url.Action</em>. Cue constructor.</p>
<pre class="brush: csharp;">public BugsController(IBugService bugService)
{
    this.bugService = bugService;

    @UrlAction = (action, controller, routeValues) =&gt;
    {
        return Url.Action(action, controller, routeValues);
    };
}</pre>
<p align="justify">Action methods are now using <em>@UrlAction</em> instead of <em>Url.Action</em> and the dependency now exists in one single place. During test, we can change the behaviour of <em>@UrlAction</em> by assigning a new delegate to it, which gives us the same flexibility as if we had been forced to create a new interface and inject a new dependency.</p>
<p align="justify">Let’s see how we can make this test pass.</p>
<pre class="brush: csharp;">[Test]
public void DeleteBug_WithValidBugID_ReturnsJsonResult()
{
    var bugService = new Mock&lt;IBugService&gt;();
    var controller = new BugController(bugService.Object); 

    controller.@UrlAction = (action, controller, routes) =&gt;
    {
        return &quot;controller/action/route&quot;;
    };

    var result = controller.DeleteBug(1); 

    Assert.IsInstanceOf&lt;JsonResult&gt;(result);
}</pre>
<p align="justify">We’re simply overwriting @UrlAction with a new delegate that returns a canned value, allowing the test to pass. It’s worth noting that a test setup would normally be used to make the test a little more quiet.</p>
<p align="justify">When you only have a few dependencies, I think this is a more elegant approach than creating wrappers and injecting them. Harry’s post goes deeper than this example shows, considering the problems that might occur if you have lots of these delegate dependencies – it’s worth a <a href="http://devhawk.net/2010/10/08/Testing+The+Untestable+With+Delegate+Injection.aspx" target="_blank">read</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://invalidcast.com/2010/10/funcy-testing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Parallel.For and Silver Bullets</title>
		<link>http://invalidcast.com/2010/08/parallel-for-and-silver-bullets/</link>
		<comments>http://invalidcast.com/2010/08/parallel-for-and-silver-bullets/#comments</comments>
		<pubDate>Fri, 13 Aug 2010 03:16:00 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">/post/ParallelFor-and-Silver-Bullets.aspx</guid>
		<description><![CDATA[I’m the first to agree that concurrency is a hard problem to solve. I have bad memories involving C, POSIX threads and mutexes that I’d rather just forget. In the end, dealing with threads sucks, we’re all just waiting for the abstraction, right? There has been some positive progress in .NET land in terms of [...]]]></description>
			<content:encoded><![CDATA[<p align="justify"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: right; border-top: 0px; border-right: 0px; padding-top: 0px" title="" border="0" alt="" align="right" src="http://invalidcast.com/wp-content/uploads/2010/10/2.png" width="96" height="96" />I’m the first to agree that concurrency is a hard problem to solve. I have bad memories involving C, POSIX threads and mutexes that I’d rather just forget. In the end, dealing with threads sucks, we’re all just waiting for the abstraction, right?</p>
<p align="justify">There has been some positive progress in .NET land in terms of making concurrency easier. We know for certain that we don’t want to be responsible for creating threads ourselves anymore, so we now have the Task Parallel Library. The TPL also includes things like <em>Parallel.For</em> and <em>Parallel.ForEach</em> for magically converting our old decrepit loops into shiny new parallel ones.</p>
<p>    <span id="more-13"></span>
<p align="justify">I bet you’re wondering how much faster one of these shiny new parallel loops can count to 1,000,000 aren&#8217;t you? Truth be told, I’ve been listening to a dangerous amount of Tina Turner and I’m in a good mood, so I’ll indulge you. Let’s do it the old decrepit way first (so we can compare).</p>
<pre class="brush: csharp; wrap-lines: false;">var timer = new Stopwatch();
timer.Start();

var countedTo = 0L;

foreach (var number in Enumerable.Range(1, 1000000))
{
    ++countedTo;
}

timer.Stop();
Console.WriteLine(&quot;Counted to {0} in {1} ms&quot;, countedTo, timer.ElapsedMilliseconds);</pre>
<p align="justify">It took a mere 11 milliseconds to count to 1,000,000.</p>
<p><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2010/10/3.png" width="279" height="108" /></p>
<p align="justify">Let’s create the parallel version. I’m terribly excited – it’s going to absolutely smash 11 ms.</p>
<pre class="brush: csharp;wrap-lines: false;">var timer = new Stopwatch();
timer.Start();

var countedTo = 0L;

Parallel.ForEach(Enumerable.Range(1, 1000000), n =&gt;
{
    ++countedTo;
});

timer.Stop();
Console.WriteLine(&quot;Counted to {0} in {1} ms&quot;, countedTo, timer.ElapsedMilliseconds);</pre>
<p align="justify">I’m on the edge of my chair. I didn’t even have to write any thread related code and I’m about to parallelise this beauty into a concurrent masterpiece. Here we go, are you ready?</p>
<p><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2010/10/4.png" width="266" height="90" /></p>
<p align="justify">Holy crap! What the hell! 116 milliseconds, are you kidding? 959,028? It hasn’t even counted to the end, there must be a bug in the framework.</p>
<p align="justify"><em>*Deep Breath*, *Deep Breath*</em></p>
<p align="justify">There’s got to be a logical explanation. It couldn’t have crashed before counting to the end, or it would have never reached the <em>Console.WriteLine</em>, right? <em>countedTo</em> holds a value less than 1,000,000, which must mean that the statement <em>++countedTo</em> was only successfully executed 959,028 times. It also took 10 times longer to run, which must mean it was doing 10 times more work.</p>
<p align="justify"><strong>Explanation</strong></p>
<p align="justify">So, it turns out <em>Parallel.ForEach</em> isn’t a silver bullet, and was never meant to be. <em>Parallel.ForEach </em>is not an abstraction, it’s simply a way of making what is already possible easier. That in itself doesn’t remove the other complexities surrounding concurrency.</p>
<p align="justify">Let’s try and make sense of why we have those results.</p>
<p align="justify">First off, the count is way off. The reason for this is quite simple once you’re aware of it. A statement such as <em>++var</em> is not atomic. An executing thread isn’t running your C# code, it’s running the machine instructions produced by your C# code. In this example, <em>++var</em> is at least three separate machine instructions, which can be interrupted at any point. The statement looks something like this to the CPU:</p>
<pre class="brush: csharp;">mov eax, dword ptr [countedTo]
add eax, 1
mov dword ptr [countedTo], eax</pre>
<p align="justify">Given that there’s only one version of <em>eax, c</em>onsider what will happen if the first thread only manages to execute the first instruction before being interrupted by the second thread which completes all three. If you’re thinking that upon the return of the first thread, the change made by the second thread will be destroyed, you’d be right. Code running inside a thread must be thread safe, irrespective of which fancy library you used to create the thread.</p>
<p align="justify">That explains why the count was way off, but why did it take 10 times longer? W<em>asn’t this thing in parallel damnit</em>? It’s important to remember that parallel doesn’t imply quicker, though in lots of cases it’s a vehicle for making an algorithm execute faster. Not everything can be parallelised, and even things that can be sometimes won’t benefit from the increased overhead of a parallel solution.</p>
<p align="justify">The problem here (besides the concurrency issue) is also one of overhead. The C# compiler is firstly having to create a closure over the <em>countedTo</em> variable in order to allow instances of the thread delegate to access it. Additionally, instead of having just three instructions to increment the count, we have all the additional instructions for managing the thread. In the end, it turns out it is actually doing 10 times more work.</p>
<p align="justify"><strong>Solution</strong></p>
<p align="justify">The solution is to synchronise the executing threads, making sure that only one thread can execute the non-thread safe code. Typically we’ll use a form of locking for this, and in fact the .NET framework allows you to use the <em>lock</em> keyword for this very purpose. Here’s how you’d correct the previous example:</p>
<pre class="brush: csharp;wrap-lines: false;">var timer = new Stopwatch();
timer.Start();

var countedTo = 0L;
var lockObject = new object();

Parallel.ForEach(Enumerable.Range(1, 1000000), n =&gt;
{
    lock (lockObject)
    {
        ++countedTo;
    }
});

timer.Stop();
Console.WriteLine(&quot;Counted to {0} in {1} ms&quot;, countedTo, timer.ElapsedMilliseconds);</pre>
<p align="justify">We’re now using an instance of System.Object to lock on, ensuring that only one thread can execute the increment at any one time. Of course, this now creates even more overhead (for such a simple operation to start with) causing it to take even longer:</p>
<p align="justify"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2010/10/5.png" width="286" height="91" /></p>
<p><strong>Conclusion</strong></p>
<p align="justify"><em>Parallel.For</em> and <em>Parallel.ForEach</em> might look like silver bullets that will magically allow you to speed up a loop by making it execute in parallel, but this isn’t the case at all. Parallel doesn’t automatically mean performance improvement. It largely depends on whether the task is inherently parallelisable and the overhead involved in achieving it.</p>
<p align="justify">You can’t simply change a <em>foreach</em> loop into a <em>Parallel.ForEach</em> loop without thinking about concurrency issues. Neither of these methods will make your code thread safe, only you can do that.</p>
<p align="justify">They weren’t kidding, concurrency isn’t a simple problem to solve.</p>
]]></content:encoded>
			<wfw:commentRss>http://invalidcast.com/2010/08/parallel-for-and-silver-bullets/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Was Dave a Genius?</title>
		<link>http://invalidcast.com/2010/07/was-dave-a-genius/</link>
		<comments>http://invalidcast.com/2010/07/was-dave-a-genius/#comments</comments>
		<pubDate>Sun, 11 Jul 2010 20:18:14 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">/post/Was-Dave-a-Genius.aspx</guid>
		<description><![CDATA[Every company you work for always seems to have a horror story about something that happened before your arrival. Things like current production old legacy systems that used mode=&#34;SQLServer&#34;&#160; for session state and then stored a ton of database reads in session to cache them. The one I remember is the story of Dave, who [...]]]></description>
			<content:encoded><![CDATA[<p align="justify"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: right; border-top: 0px; border-right: 0px; padding-top: 0px" title="" border="0" alt="" align="right" src="http://invalidcast.com/wp-content/uploads/2010/10/a1.png" width="83" height="73" />Every company you work for always seems to have a horror story about something that happened before your arrival. Things like <strike>current production</strike> old legacy systems that used <em>mode=&quot;SQLServer&quot;&#160; </em>for session state and then stored a ton of database reads in session to <em>cache</em> them.</p>
<p align="justify">The one I remember is the story of Dave, who had recently discovered the power of <em>document.write</em> and took it a little too far. <em>Why have the server do all the work when the client can do it instead?</em> Dave decided to have the server <em>response.write</em> a metric ton of <em>document.write </em>statements which would then produce the page at runtime in the browser. It’s possible he may have been thinking too hard about what <a href="http://en.wikipedia.org/wiki/David_Wheeler_(computer_scientist)" target="_blank">David Wheeler</a> said about indirection.</p>
<p>    <span id="more-14"></span>
<p align="justify">Back when JavaScript in the browser made people as nervous as a small nun at a penguin shooting, this story was pretty funny. But with the advances of in-browser JavaScript since the days of <em>DHTML</em> and the widespread popularity of libraries like jQuery, perhaps (and I may be giving him too much credit here) Dave was just ahead of his time.</p>
<p align="justify">When it comes to rendering, either the server does it in full, the server does most of it and the client helps out, or the client does it in full (with the exception of the initial HTML document sent down on the first request). I carefully ordered these options to reflect the trend in the way web applications seem to be moving.</p>
<p align="justify">Go back 10 years and it was unheard of for a web application to be client-centric, where most of the rendering was done by JavaScript in the browser. They weren’t even called web applications, they were web sites. Fast forward to today and you see more and more involvement by the client as we start to realise the benefits of client rendering. Due to the lack of acronyms at the time, we also gave the idea a new name <a href="http://en.wikipedia.org/wiki/Ajax_(programming)" target="_blank">Ajax</a>.</p>
<p align="justify">But why do we want the client to be responsible for rendering? While it’s easier to have the server to do it, the client has a few advantages over the server. The client can render things faster because it doesn’t require a round trip back to the server to get the content. The reduction in round trips also means less data is sent and received.</p>
<p align="justify">But what price do we pay for rendering content more quickly and reducing the amount of data sent/received? If it was up to Dave it would be a pretty high one, but fortunately things have changed since <em>document.write</em>. Let’s do an experiment to see how the rendering of content might evolve from server to client.</p>
<p><strong>The Application</strong></p>
<p align="justify">Let’s build a really simple <em>To Do</em> application that will list our current items and allow us to submit new ones.</p>
<p><strong>Server Rendering</strong></p>
<p align="justify">We’ll start the experiment by creating the server-rendered version. A plain old <em>&lt;form&gt;</em> will post new items to the server and we’ll use the post/redirect/get pattern to redirect the browser back to the page that shows the current list of submissions.</p>
<p>First up, we’ve got the controller:</p>
<pre class="brush: csharp; ruler: true;">public class TodoController : Controller
{
    public ActionResult Index()
    {
        return View(Database.GetAll());
    }

    [HttpPost]
    public ActionResult Index(string task)
    {
        Database.Add(new Todo() { Task = task, Created = DateTime.Now });
        return RedirectToAction(&quot;Index&quot;);
    }
}</pre>
<p align="justify">We are using an in-memory database to hold the current list of submissions. When the client posts a new todo item we add it to the database and then redirect back to the action that displays the current list:</p>
<pre class="brush: xml; ruler: true;">&lt;ul&gt;

&lt;% foreach (var item in Model) { %&gt;

     &lt;li&gt;
         &lt;b&gt;&lt;%= item.Created.ToShortTimeString() %&gt;&lt;/b&gt; &lt;%= item.Task %&gt;
     &lt;/li&gt;

&lt;% } %&gt;

&lt;/ul&gt;

&lt;% using (Html.BeginForm()) { %&gt;

     &lt;input name=&quot;task&quot; /&gt;
     &lt;input type=&quot;submit&quot; value=&quot;Add ToDo&quot; /&gt;

&lt;% } %&gt;</pre>
<p align="justify">And it comes to life:</p>
<p><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2010/10/a2.png" width="281" height="196" /></p>
<p align="justify">Let’s record some numbers so we can measure any changes in performance with later versions. Firstly, let’s see how many bytes are being received for the initial page load. We’ll then submit three new items and see what happens.</p>
<p><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2010/10/a3.png" width="544" height="232" /></p>
<p align="justify">The first request shows the initial page load of 763 bytes. We then see 3 blocks of post/redirect/get in which the browser downloads 841 bytes, then 919 bytes and finally 997 bytes (the constant increase of 78 bytes is because the three todo items posted were exactly the same length). In the end, posting 3 new todo items resulted in the client downloading a total of 3,520 bytes and making 3 roundtrips to the server for rendering.</p>
<p><strong>Client Rendering</strong></p>
<p align="justify">Redirecting right after the POST allowed us to put the client back into a consistent state with the new data. If the client is to handle rendering, the client needs to know how to produce this new UI state too. In addition to rendering, the client also needs to be able to asynchronously update the server with new data and be able to request the set of existing data. It’s a hard life being the client.</p>
<p align="justify">The first thing we need to do to support updates from the client asynchronously is remove the redirect from the POST action (since the client won’t redirecting anymore). We’ll also need a new action for returning the current set of todo items, allowing the client to update the UI on the first request and any time afterwards.</p>
<pre class="brush: csharp; ruler: true;">public class TodoController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public JsonResult GetAll()
    {
        return Json(Database.GetAll(), JsonRequestBehavior.AllowGet);
    }

    [HttpPost]
    public void Add(string task)
    {
        Database.Add(new Todo() { Task = task, Created = DateTime.Now });
    }
}</pre>
<p align="justify">Now that the controller is set up for asynchronous requests from the client, we need to modify the view to support client rendering. The first thing we’ll do is remove the server tags from the previous example, since the client will be creating that content. Similarly we won’t need the form either.</p>
<pre class="brush: xml; ruler: true;">&lt;ul&gt;&lt;/ul&gt;

&lt;input id=&quot;task&quot; name=&quot;task&quot; /&gt;
&lt;input id=&quot;submitButton&quot; type=&quot;submit&quot; value=&quot;Add ToDo&quot; /&gt;</pre>
<p align="justify">The view got a lot smaller, but we’re not done yet. Let’s use jQuery to add a page load handler which will request the current list of todo items and add them to the empty <em>&lt;ul&gt;</em>.</p>
<pre class="brush: xml; ruler: true; wrap-lines: false;">&lt;script type=&quot;text/javascript&quot;&gt;

    $(function () {
        $.getJSON(&quot;/Todo/GetAll&quot;, function (items) {
            $(items).each(function () {
                $(&quot;ul&quot;).append(&quot;&lt;li&gt;&lt;b&gt;&quot; + this.Created + &quot;&lt;/b&gt; &quot; + this.Task + &quot;&lt;/li&gt;&quot;);
            });
        });
    });

&lt;/script&gt;</pre>
<p align="justify">That should cover the rendering part, but we also need to handle submitting new items. Let’s add a handler to the submit button that reads the value and posts it back to the server.</p>
<pre class="brush: xml; ruler: true; wrap-lines: false;">&lt;script type=&quot;text/javascript&quot;&gt;

    $(function () {
        $.getJSON(&quot;/Todo/GetAll&quot;, function (items) {
            $(items).each(function () {
                $(&quot;ul&quot;).append(&quot;&lt;li&gt;&lt;b&gt;&quot; + this.Created + &quot;&lt;/b&gt; &quot; + this.Task + &quot;&lt;/li&gt;&quot;);
            });
        });

        $(&quot;#submitButton&quot;).click(function () {
            $.post(&quot;/Todo/Add&quot;, { Task: $(&quot;#task&quot;).val() }, function () {
                // todo (no pun intended)
            });
        });
    });

&lt;/script&gt;</pre>
<p align="justify">We can now post a new todo item to the server, but what about the client state? We have a couple of options here. We could extract just the code from line 6 into a new function and have the client add an <em>&lt;li&gt;</em> when it posts the new todo, or we could extract the code from line 4 to line 8 and have the client re-render the entire list when it posts the new todo (if the new item caused all the others to change for example). In this particular case the former option suits us best, so let’s do that.</p>
<pre class="brush: xml; ruler: true; wrap-lines: false;">&lt;script type=&quot;text/javascript&quot;&gt;

    $(function () {
        $.getJSON(&quot;/Todo/GetAll&quot;, function (items) {
            $(items).each(function () {
                insertTodo(this);
            });
        });

        $(&quot;#submitButton&quot;).click(function () {
            var todo = { Task: $(&quot;#task&quot;).val(), Created: &quot;Just Now&quot; };
            $.post(&quot;/Todo/Add&quot;, todo, function () {
                insertTodo(todo);
            });
        });
    });

    function insertTodo(toDo) {
        $(&quot;ul&quot;).append(&quot;&lt;li&gt;&lt;b&gt;&quot; + toDo.Created + &quot;&lt;/b&gt; &quot; + toDo.Task + &quot;&lt;/li&gt;&quot;);
    }

&lt;/script&gt;</pre>
<p align="justify">And we’re done. The client now only sends and receives the data it needs and benefits from the much faster rendering (with the exception of the first page load).</p>
<p><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2010/10/a4.png" width="312" height="228" /></p>
<p align="justify">And here’s how the raw requests look:</p>
<p><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2010/10/a5.png" width="541" height="167" />&#160;</p>
<p align="justify">The first request is now considerably larger than before because it contains the JavaScript client rendering code, but looking at the other requests we see that the server sent down 1,373 bytes in total (39% of the server-rendered version).</p>
<p align="justify">Unlike the server-rendered version, there was no need for a GET after each of the three POST requests, saving the server 3 rendering jobs and the bandwidth needed to send that data back. There is also the benefit of instant feedback to the client, since it’s not having to wait for the server to render the results.</p>
<p align="justify"><strong>What’s The Cost?</strong></p>
<p align="justify">Simplicity has been traded off for responsiveness and bandwidth. Letting the server handle rendering was easier to understand and contained less moving parts, while on the other hand, letting the client handle rendering allowed for a leaner application which put less load on the server and resulted in a lightning fast experience for the user.</p>
<p align="justify">You may be thinking <em>but do I want the simple solution, or the solution that is lightning fast? </em>The question I have is <em>how can we have both?</em></p>
<p align="justify"><strong>Where’s The Complexity?</strong></p>
<p align="justify">When the controller was modified to support the asynchronous client, it didn’t really become any more complex. In fact, I think I prefer it in its current state – it now looks like a basic data access API. However, when we changed the view (by introducing the JavaScript) it became considerably more complex. So what’s making the view more complex and how can we solve it?</p>
<p align="justify">Originally I thought <em>well, of course, it’s all the jQuery</em>, but when I thought about it a little more I realised it’s not jQuery that is introducing the complexity for client rendering – that has been there all along. If anything, jQuery is making it easier than it would have been otherwise. The problem is the level of indirection that we are working at in the current solution.</p>
<p align="justify">Manually adding, editing and removing lots of individual elements of the DOM is akin to when we used to declare a pointer, ask for some memory, copy a value into it and then make sure it was correctly terminated in order to store a string; it’s too low level and fiddly. We need another layer of indirection.</p>
<p align="justify"><strong>Templating</strong></p>
<p align="justify">Rather than getting down and dirty with the DOM, I think I’d much rather create an association between a data model and a visual template. When the data model is modified, either through something being added, removed or changed, the visual template should simply be able to re-render itself to reflect those changes.</p>
<p align="justify">JavaScript templating is a relatively new area of experimentation, but there are still a number of options. We’ll use the jQuery templating library <a href="http://github.com/jquery/jquery-tmpl" target="_blank">jquery-tmpl</a> for this example. Let’s replace the manual DOM manipulation code with templating:</p>
<pre class="brush: xml;">&lt;ul&gt;&lt;/ul&gt;

&lt;input id=&quot;task&quot; name=&quot;task&quot; /&gt;
&lt;input id=&quot;submitButton&quot; type=&quot;submit&quot; value=&quot;Add ToDo&quot; /&gt;

&lt;script id=&quot;todoTemplate&quot; type=&quot;text/html&quot;&gt;

    &lt;li&gt;&lt;b&gt;${Created}&lt;/b&gt; ${Task}&lt;/li&gt;

&lt;/script&gt;

&lt;script type=&quot;text/javascript&quot;&gt;

    var model;

    $(function() {
        model = {
            data: &lt;%= new JavaScriptSerializer().Serialize(Model) %&gt;,
            add: function() {
                var todo = { Task: $(&quot;#task&quot;).val(), Created: &quot;Just Now&quot; };
                $.post(&quot;/Todo/Add&quot;, todo, function() {
                    model.data.push(todo);
                    model.render();
                });
            },
            render: function() {
                $(&quot;ul&quot;).html(&quot;&quot;);
                $(&quot;#todoTemplate&quot;).render(model.data).appendTo(&quot;ul&quot;);
            }
        };

        $(&quot;#submitButton&quot;).click(function() {
            model.add();
        });

        model.render();
    });

&lt;/script&gt;</pre>
<p align="justify">The initial mark-up is unchanged. We still have the empty list and the two inputs for adding new todo items. Starting on line 6 we create the client-side template that will be used to render the data.</p>
<p align="justify">The biggest change is the script. We’re creating the model on line 17 and supplying the initial set of data from the server (meaning we save a request and don’t need the getAll method). Notice how there is no jQuery code to manually add DOM elements now. Instead the item is added to the model and the template is simply re-rendered.</p>
<p align="justify"><strong>Can This Be Improved?</strong></p>
<p align="justify">There is a definite improvement when we compare the current version with the original client-rendered version. We are no longer having to write code to manually create individual elements as we’re using a template to keep that in one place. Because the template is rendered directly from the model, adding, editing and removing items all share the same rendering logic (which saves lots of manual DOM manipulation).</p>
<p align="justify">However, when it comes to adding a new item, we’re still having to write code to read the value from the UI, add it to the model and tell the template to re-render itself. Another problem is that the data is bound only one way. If the todo items were editable, modifying one of them would not update the underlying model.</p>
<p align="justify">How can we go one step further?</p>
<p><strong>JavaScript With Observers</strong></p>
<p align="justify">At the moment the solution can be thought of as a pull-based system. That is, when something changes we pull the new values from the UI and update the model data ourselves. But what if the idea was reversed – what if, when a value changed, our model knew about that change immediately because the new value was pushed into it? Well, it would mean we didn’t need to write pulling code anymore (reading from the DOM manually). Ideally, we wouldn’t even need to tell the template to re-render itself. Best of all we could write less code.</p>
<p align="justify">A number of libraries are already emerging that support this observable pattern of building rich client applications in the browser. Recently <a href="http://blog.stevensanderson.com/" target="_blank">Steve Sanderson</a> announced his own library, <a href="http://blog.stevensanderson.com/2010/07/05/introducing-knockout-a-ui-library-for-javascript/" target="_blank">Knockout</a>. Taken from his introductory post:</p>
<blockquote>
<p>Knockout is an open-source JavaScript library that makes it easier to create rich, desktop-like user interfaces with JavaScript and HTML, using observers to make your UI automatically stay in sync with an underlying data model. It works particularly well with the MVVM pattern, offering declarative bindings somewhat like Silverlight but without the browser plugin.</p>
</blockquote>
<p align="justify">From the short amount of time I’ve had to look at Knockout, I have to say that it’s pretty awesome. There’s no point in paraphrasing what Steve has already said, so I urge you to go read <a href="http://blog.stevensanderson.com/2010/07/05/introducing-knockout-a-ui-library-for-javascript/" target="_blank">his blog post about it</a> and see for yourself.</p>
<p align="justify">Back to the problem at hand, how does Knockout help? Let’s identify the problems with the current solution:</p>
<ul>
<li>
<div align="justify">The <em>add </em>function is concerned with locating and reading the new todo data directly from the UI; it’s coupled to the presentation. </div>
</li>
<li>
<div align="justify">The very fact we need a render method isn’t good – why should we need one? It would be better if the template re-rendered itself automatically when the model data changed. </div>
</li>
<li>
<div align="justify">Let’s say we add a new feature where all current todo items are made editable. We’re then going to have to write more code to pull those values back into the model when they are modified.</div>
</li>
</ul>
<p align="justify">How does Knockout solve these problems?</p>
<p align="justify">The <em>add</em> function no longer needs to be concerned with locating the new data, instead it will be pushed into an observable within the view model through <a href="http://knockoutjs.com/examples/controlTypes.html" target="_blank">Knockout’s various bindings</a>. Say goodbye to the <em>render </em>method too, we won’t be needing that – templates are automatically re-rendered when Knockout detects that the observable they are associated with has been modified. Finally, if we make the todo items editable, Knockout’s two-way binding means that any changes we make in the UI will automagically end up back in the model. Similarly, if we change the model data (perhaps we have a background timer that is updating from the server) the UI will reflect those changes without us having to write a single additional line of code.</p>
<p align="justify">Here’s a Knockout version (pun intended):</p>
<pre class="brush: xml; ruler: true; wrap-lines: false;">&lt;ul data-bind=&quot;template: { name: 'todoTemplate', foreach: todos }&quot;&gt;&lt;/ul&gt;

&lt;input data-bind=&quot;value: newTodo&quot; /&gt;
&lt;input data-bind=&quot;click: addTodo&quot; type=&quot;submit&quot; value=&quot;Add ToDo&quot; /&gt;

&lt;script id=&quot;todoTemplate&quot; type=&quot;text/html&quot;&gt;

    &lt;li&gt;&lt;b&gt;${Created}&lt;/b&gt; ${Task}&lt;/li&gt;

&lt;/script&gt;

&lt;script type=&quot;text/javascript&quot;&gt;

    $(function() {
        var model = {
            todos: ko.observableArray(&lt;%= new JavaScriptSerializer().Serialize(Model) %&gt;),
            newTodo: ko.observable(&quot;&quot;),
            addTodo: function () {
                this.todos.push({ Task: this.newTodo(), Created: &quot;Just Now&quot; });
                $.post(&quot;/Todo/Add&quot;, { Task: this.newTodo() });
            }
        };

        ko.applyBindings(document.body, model);
    });

&lt;/script&gt;</pre>
<p align="justify">You’ll notice that the <em>&lt;input&gt;</em> and <em>&lt;ul&gt;</em> elements now have <em>data-bind</em> attributes. The <em>data-bind</em> attribute tells Knockout how the element interacts with the view model. In the case of the <em>&lt;ul&gt; </em>element, the <em>data-bind</em> attribute is specifying that it is bound to each item of the collection named <em>todos</em> and that each item should be rendered using the template named <em>todoTemplate</em><em>.</em></p>
<p align="justify">The first <em>&lt;input&gt; </em>element has a <em>value</em> binding that links the value of the element with the observable named <em>newTodo. </em>When a new value is entered into the <em>&lt;input&gt;</em>, it is also pushed into the observable. The second <em>&lt;input&gt;</em> element has a <em>click</em> binding that links it to the <em>addTodo</em> function in the view model.</p>
<p align="justify">The script has been reduced even further and now only contains the declaration of a view model and a call to the <em>applyBindings</em> method. Notice how the <em>todos</em> collection and the <em>newTodo</em> field are observables. Observables are key to allowing Knockout to push changing values in the UI back into the model and propagate changes in the model back to the UI.</p>
<p><strong>Conclusion</strong></p>
<p align="justify">We’ve seen how a simple todo application has gone from being rendered on the server to being rendered on the client. Moving the rendering down to the client has some advantages, such as a snappier user experience and less overhead in terms of bandwidth/reducing requests (post/redirect/get).</p>
<p align="justify">Moving logic onto the client also introduced some additional problems, such as having to be concerned with updating the client UI state independently of the server. However, as we refined the solution we were able to swap out manual DOM manipulation and state coupled with UI elements for a more decoupled solution through the use of the Knockout library. Knockout bridges the gap between the UI and the data model by keeping the two cleanly separated while still allowing a high degree of interactivity between the two through observable collections and various UI bindings.</p>
<p align="justify">In the end, the client solution was clean and pretty straightforward, making a good case for future situations where building some functionality on the client would be desirable, but would have otherwise been avoided because of the complexity of interacting with the DOM (in both directions).</p>
<p align="justify">As support for JavaScript explodes in the browser, more and more opportunities are emerging for cool things to be done on the client with the same compatibility you’d get from the server-based alternatives. We’re in an exciting time where we’ll see people really pushing to get the most out of the client, rather than just using it as a viewer for content rendered only by the server.</p>
<p align="justify">Getting back to the underlying question, was Dave really a genius? In order to accurately and fairly answer the question, I consulted a magic 8 ball. The answer: <em>don’t count on it</em>.</p>
]]></content:encoded>
			<wfw:commentRss>http://invalidcast.com/2010/07/was-dave-a-genius/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>The &quot;if it isn&#8217;t broken, don&#8217;t fix it&quot; Mentality</title>
		<link>http://invalidcast.com/2010/06/the-if-it-isnt-broken-dont-fix-it-mentality/</link>
		<comments>http://invalidcast.com/2010/06/the-if-it-isnt-broken-dont-fix-it-mentality/#comments</comments>
		<pubDate>Fri, 11 Jun 2010 09:52:48 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">/post/The-if-it-isnt-broken-dont-fix-it-mentality.aspx</guid>
		<description><![CDATA[Today I realised that every time I hear the phrase if it isn&#8217;t broken, don&#8217;t fix it I feel kind of uncomfortable. I fully understand the notion: the process yields the results we want, so why bother?&#160; As it is being said, I detect the whatever works attitude emanating from the person saying it. No [...]]]></description>
			<content:encoded><![CDATA[<p align="justify"><img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px 0px 0px 15px; padding-left: 0px; padding-right: 0px; display: inline; float: right; border-top: 0px; border-right: 0px; padding-top: 0px" title="" border="0" alt="" align="right" src="http://invalidcast.com/wp-content/uploads/2010/10/b1.jpg" width="84" height="76" />Today I realised that every time I hear the phrase <strong>if it isn&#8217;t broken, don&#8217;t fix it </strong>I feel kind of uncomfortable. I fully understand the notion: t<em>he process yields the results we want, so why bother?</em>&#160;</p>
<p align="justify">As it is being said, I detect the <em>whatever works </em>attitude emanating from the person saying it. No concept of continuous improvement. No interest in reflecting. Not even 60 seconds invested to consider whether the process is efficient or could be improved. It most cases it’s almost a canned response to any comment referring to the efficiency of a process that is considered to be <em>working</em>.</p>
<p>    <span id="more-15"></span>
<p align="justify">Maybe the process breaks once per month, causing Fred to stop what he’s doing (see <a href="http://www.codinghorror.com/blog/2006/09/the-multi-tasking-myth.html" target="_blank">Gerald Weinberg’s rule of thumb</a>) and fix it. <em>But, who cares, it works, and Fred doesn’t mind. </em>Paper-based filing systems, typewriters and horse and cart <em>worked </em>but this didn’t exclude them all from being significantly improved by someone with the right mindset.</p>
<p align="justify">Applying the <strong>if it isn’t broken, don’t fix it </strong>mentality to everything is naïve; you end up with lots of suboptimal processes. Based on the fact that you never get it right the first time, processes need to evolve, and for this to happen a culture of reflection and improvement must exist.</p>
<p align="justify">To consider something to be either <em>working</em> or <em>broken</em> is a simple model which doesn’t leave much room for improvement. Considering the degree to which something is <em>working</em> is a better model that puts your mind in the right place. How reliable is the process? Can it execute quicker? Can the execution cost be reduced? We need to think about quality, not just if by some vague definition the process can be considered to be <em>working</em>.</p>
<p align="justify">I recently finished reading <a href="http://www.amazon.com/Toyota-Way-Jeffrey-Liker/dp/0071392319" target="_blank">The Toyota Way</a>. In the book, Jeffrey Liker explains the management philosophy behind Toyota. Interestingly, one of the principles within Toyota is to “b<em>uild a culture of stopping to fix problems, to get quality right the first time”. </em>Liker goes on to explain the apparent productivity paradox:</p>
<blockquote><p align="justify">Toyota management say that it&#8217;s OK to run at less than 100% of the time, even when it&#8217;s possible to run full time, yet Toyota is regularly ranked amongst the most productive plants in the auto industry. Why?</p>
</blockquote>
<p align="justify">Investing time and effort into quality from the start sounds like the slower and more expensive method to most people. <em>Let’s just get something working and improve it later.</em> The problem is, too many people don’t improve it later. The <strong>If it isn’t broken, don’t fix it</strong> syndrome starts instead. Liker explains how Toyota does it:</p>
<blockquote><p align="justify">Because Toyota learned long ago that solving quality problems at the source saves time and money downstream. By continually surfacing problems and fixing them as they occur, you eliminate waste, your productivity soars and competitors who are running assembly lines flat-out and letting problems accumulate get left in the dust.</p>
</blockquote>
<p align="justify">The issue of letting quality problems accumulate isn’t exclusive to the auto industry. In the software industry it results in poorly written systems being built on top of other poorly written systems that, while completed sooner than a higher quality system might have been, require increasing amounts of human attention as the accumulation of quality problems becomes too big to ignore; too big to be considered <em>working.</em> Needless to say, the cost of running these systems starts to increase too.</p>
<p align="justify">So from now on, <strong>if it isn’t broken, don’t fix it</strong> is banned. Stop using it. It makes you sound like you don’t care even enough to look for improvement. Things are not <em>broken</em> or <em>working</em>; they are <em>broken </em>or <em>working</em> to a certain degree and may be exposing opportunities to be improved and have their business value increased. It’s also a mistake to assume that business value can’t be increased from existing work (or processes) rather than business value just coming from new work.</p>
<p align="justify">You can be the one who thoughtfully creates work to a high standard, always looking to improve yourself and increase the business value in suboptimal existing work. Alternatively, be the one who doesn’t care enough to even look for improvement opportunities and would rather just churn out first versions and move on – leaving a legacy of low quality behind you.<em> </em>It’s your choice.</p>
<p align="justify"><strong>If it isn’t broken, fix it anyway.</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://invalidcast.com/2010/06/the-if-it-isnt-broken-dont-fix-it-mentality/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>A Gentle Introduction to WCF</title>
		<link>http://invalidcast.com/2010/04/a-gentle-introduction-to-wcf/</link>
		<comments>http://invalidcast.com/2010/04/a-gentle-introduction-to-wcf/#comments</comments>
		<pubDate>Sun, 25 Apr 2010 18:20:00 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">/post/A-Gentle-Introduction-to-WCF.aspx</guid>
		<description><![CDATA[I was thinking to myself the other day, &#34;you know, I haven&#8217;t written any socket code in years&#34;. A few weeks before I&#8217;d been thinking the same thing about threads. It&#8217;s probably a good thing that I haven&#8217;t, sockets and threads can get complicated and there are now powerful libraries built on top of that [...]]]></description>
			<content:encoded><![CDATA[<p>I was thinking to myself the other day, &quot;<em>you know, I haven&#8217;t written any socket code in years</em>&quot;. A few weeks before I&#8217;d been thinking the same thing about threads. It&#8217;s probably a good thing that I haven&#8217;t, sockets and threads can get complicated and there are now powerful libraries built on top of that stuff that safely abstract it away. You have to admit though, it used to be fun :)</p>
<p align="justify">Well, it started out fun. Pretty quickly you’d realise that using sockets for IPC sucks much more quickly than you expected. For starters, you didn’t have any kind of protocol between the two processes so you’d invent your own. You would do horrible things like receiving a length-prefixed string over the socket and doing a switch statement to determine which method should be called.</p>
<p>    <span id="more-16"></span>
<p align="justify">It&#8217;s likely that designing a socket protocol so that one process can effectively call a method in another process is not the kind of problem you intended to spend your time solving. Fortunately we now have solid frameworks that handle this lower level stuff for us and let us focus on defining what the methods we&#8217;ll be calling across process (or indeed across the internet) actually do.</p>
<p><strong>Enter WCF</strong></p>
<p align="justify">The Windows Communication Foundation is Microsoft&#8217;s offering to us .NET folks for building service-oriented applications. For those of you who aren&#8217;t familiar with the concept of service-oriented architecture, think of it like this: instead of building your business logic as a set of classes in an assembly, we build them as a set of independent services that we make available as an API (just like a twitter client does its work via the twitter API).</p>
<p align="justify">The first time I heard about SOA, I thought it was just a <em>big grand enterprise-only thing</em> and never considered it relevant to the tiny little applications I was building. However, it turns out that thinking of your classes as services is a powerful concept that is applicable in lots of situations. I now use a service architecture to allow javascript to talk to the web application and to allow the web application to talk to windows services.</p>
<p align="justify">Some even suggest that <a href="http://www.dotnetrocks.com/default.aspx?showNum=520">every class should be a WCF service</a>, and indeed why shouldn’t a class have a platform-independent endpoint that allows anyone to call it?</p>
<p><strong>WCF Basics</strong></p>
<p align="justify">A WCF service is primarily made up of two parts. First is the service contract, which is just an interface that specifies which methods are available in the service. Second is the service implementation class that implements the service contract interface. <a href="http://lkml.org/lkml/2000/8/25/132" target="_blank">Talk is cheap. Show me the code.</a></p>
<p align="justify">Let’s create a WCF service for telling jokes. First we’ll create the service contract (the interface).</p>
<pre class="brush: csharp;">[ServiceContract]
public interface IJokeService
{
    [OperationContract]
    string GetLawyerJoke();

    [OperationContract]
    string GetRandomJoke();
}</pre>
<p align="justify">Notice the [ServiceContract] attribute denoting that the interface is a WCF service contract and the [OperationContract] attributes on each method indicating that the method will be available to clients. If you leave out an [OperationContract] attribute, the method won’t be available over the service.</p>
<p align="justify">So let’s create an implementation of the service.</p>
<pre class="brush: csharp;">public class JokeService : IJokeService
{
    public string GetLawyerJoke()
    {
        return &quot;Why did God make snakes before lawyers? To practice.&quot;;
    }

    public string GetRandomJoke()
    {
        return &quot;Where do you find a one legged dog? Where you left it.&quot;;
    }
}</pre>
<p align="justify">You <strong>lol</strong>ed, admit it. We’ve now created a service contract and implemented that contract with our JokeService. But how does someone actually use the service?</p>
<p align="justify"><strong>Hosting WCF Services</strong></p>
<p align="justify">The next step in building our WCF service is to make it available to clients by hosting it. There are various options for hosting WCF services, including hosting them in IIS and self-hosting them within the application domain (which is particularly useful for things like IPC). For the purpose of this simple example, we’ll see how to self-host the service in a basic console application.</p>
<p align="justify">First let’s create a new console application and add our WCF service to it.</p>
<p><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2010/10/c1.png" width="223" height="159" /></p>
<p align="justify">Self-hosting the service is made possible by the ServiceHost class. The theory goes like this: <strong>create an instance</strong> of the ServiceHost class, <strong>add an endpoint</strong> to it and finally<strong> open it</strong>. Let’s see how that’s done.</p>
<pre class="brush: csharp; wrap-lines: false;">class Program
{
    static void Main(string[] args)
    {
        ServiceHost serviceHost = new ServiceHost(typeof(JokeService), new Uri[] { new Uri(&quot;http://localhost:4242&quot;) });
        serviceHost.AddServiceEndpoint(typeof(IJokeService), new BasicHttpBinding(), &quot;JokeService&quot;);
        serviceHost.Open();

        Console.ReadKey();
        serviceHost.Close();
    }
}</pre>
<p align="justify">On line 5 we create a ServiceHost for the JokeService and specify that the base address of the service will be located at <em>http://localhost:4242. </em>On line 6 we add an HTTP endpoint to the ServiceHost which makes the IJokeService contract available over HTTP at the address <em>http://localhost:4242/JokeService</em>. Finally, on line 7 the service is opened and available to clients.</p>
<p><strong>Consuming WCF Services</strong></p>
<p align="justify">Now that we have a self-hosted WCF service, let’s see how a client can interact with it. There are two situations worth considering in terms of the client. The client may be an external third party and have access to nothing more than the URL of the service. On the other hand, the client may be another process that has access to the service contract interface.</p>
<p align="justify">In the case of a local client (one with access to the contract interface), the service can be called without consuming the metadata and automatically building calling code via the svcutil.exe utility. We’ll see how to do this in a second. Where the client is an external third party, the service must expose its metadata so that the third party knows how to interact with the service. We’ll see how to achieve this too.</p>
<p><strong>Consuming Local WCF Services</strong></p>
<p align="justify">Let’s build another console application for consuming the JokeService. For the sake of simplicity, we’ll also copy the WCF service contract into this project (in reality it’s more likely the contract would be built into some shared assembly that you’d reference instead).</p>
<p><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2010/10/c2.png" width="246" height="158" /></p>
<p align="justify">Because we have access to the IJokeService contract, we can ask the lovely ChannelFactory class to create a channel that lets us access the service by its known endpoint address and binding.</p>
<pre class="brush: csharp; wrap-lines: false;">class Program
{
    static void Main(string[] args)
    {
        ChannelFactory&lt;IJokeService&gt; factory = new ChannelFactory&lt;IJokeService&gt;();
        factory.Endpoint.Binding = new BasicHttpBinding();
        factory.Endpoint.Address = new EndpointAddress(&quot;http://localhost:4242/JokeService&quot;);

        IJokeService jokeService = factory.CreateChannel();

        Console.WriteLine(jokeService.GetLawyerJoke());
        Console.WriteLine(jokeService.GetRandomJoke());
    }
}</pre>
<p align="justify">And as long as our WCF service host application is running, we get the following output.</p>
<p><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2010/10/c3.png" width="470" height="142" /></p>
<p align="justify">I don’t know about you, but I certainly prefer this to writing my own socket protocol. So, what if we don’t have access to the service contract?</p>
<p><strong>Consuming Remote WCF Services</strong></p>
<p align="justify">It may be the case that we’re offering our service to a third party and they don’t have access to our code in order to use the ChannelFactory approach. In these situations we have to make available the service metadata so that third parties can use utilities such as svcutil.exe to query it and scaffold client code.</p>
<p align="justify">Unlike ASMX web services, WCF services don’t make their metadata available by default. Fortunately, it’s pretty easy to add an additional endpoint that offers metadata and that’s what we’re going to do now. As a quick reminder, here’s our service hosting code from earlier.</p>
<pre class="brush: csharp; wrap-lines: false;">class Program
{
    static void Main(string[] args)
    {
        ServiceHost serviceHost = new ServiceHost(typeof(JokeService), new Uri[] { new Uri(&quot;http://localhost:4242&quot;) });
        serviceHost.AddServiceEndpoint(typeof(IJokeService), new BasicHttpBinding(), &quot;JokeService&quot;);
        serviceHost.Open();

        Console.ReadKey();
        serviceHost.Close();
    }
}</pre>
<p align="justify">Between lines 6 and 7 we’re going to add a new endpoint for <strong>mex </strong>(metadata exchange). But before we can add a mex endpoint we also need to add a service behaviour so that clients can issue an HTTP GET to request the service metadata.</p>
<pre class="brush: csharp; wrap-lines: false;">class Program
{
    static void Main(string[] args)
    {
        ServiceHost serviceHost = new ServiceHost(typeof(JokeService), new Uri[] { new Uri(&quot;http://localhost:4242&quot;) });
        serviceHost.AddServiceEndpoint(typeof(IJokeService), new BasicHttpBinding(), &quot;JokeService&quot;);

        serviceHost.Description.Behaviors.Add(new ServiceMetadataBehavior()
        {
            HttpGetEnabled = true
        });

        serviceHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexHttpBinding(), &quot;mex&quot;);
        serviceHost.Open();

        Console.ReadKey();
        serviceHost.Close();
    }
}</pre>
<p align="justify">The WCF service is now configured to allow its metadata to be retrieved by clients. If we browse to the service URL in a web browser we see the following:</p>
<p><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2010/10/c4.png" width="476" height="206" /></p>
<p align="justify">WCF is helpfully telling us that clients may use the svcutil.exe utility to generate calling code. So let’s modify our original console application to use the metadata to generate code rather than using the ChannelFactory. Firstly we’ll delete the reference to the service contract (as we should get everything from the service metadata now) and we’ll delete all the ChannelFactory code too.</p>
<p align="justify">While we can use svcutil.exe to generate the client code, we can also use the <em>Add Service Reference</em> option from Visual Studio too. Both do the same thing.</p>
<p><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2010/10/c5.png" width="266" height="204" /></p>
<p align="justify">I’m not sure it could get much easier than this without Visual Studio having some kind of mind reading functionality in the next release. Anyway, we’re now asked where the service is located.</p>
<p><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="" border="0" alt="" src="http://invalidcast.com/wp-content/uploads/2010/10/c6.png" width="523" height="205" /></p>
<p align="justify">Don’t forget, the service host application must still be running for Visual Studio to find it and generate the client code. It looks like the service was found, so let’s add that to the project. In whichever namespace you chose, you should now have a JokeServiceClient that was built from the service’s metadata. Here’s what the new client looks like.</p>
<pre class="brush: csharp; ruler: true;">class Program
{
    static void Main(string[] args)
    {
        JokeServiceClient jokeService = new JokeServiceClient();

        Console.WriteLine(jokeService.GetLawyerJoke());
        Console.WriteLine(jokeService.GetRandomJoke());
    }
}</pre>
<p><b>The Recapitulation</b></p>
<p align="justify">In this simple introduction we’ve seen how to create a WCF service and self-host it in a console application. WCF services can also be hosted in IIS as well as within other application types (WPF/Windows Services/WinForms) making them ideal for IPC.</p>
<p align="justify">Consuming a WCF service is also relatively easy, even if you’re a third party without access to the binary service contract. We saw how to manually call the service with the help of the WCF ChannelFactory. We also saw how to enable metadata exchange (mex) to allow third parties to interface with our service.</p>
<p align="justify">WCF goes much deeper than this simple overview demonstrates, allowing you to control fine-grained aspects of your service such instancing, security, concurrency and transactions and in that regard WCF is a much better solution for service-oriented applications than something like ASMX.</p>
<p align="justify">It’s worth noting that the configuration of a WCF service can also be specified in the application’s configuration file. Examples in this post have configured the service programmatically in an attempt to better explain what’s involved in creating and consuming WCF services.</p>
]]></content:encoded>
			<wfw:commentRss>http://invalidcast.com/2010/04/a-gentle-introduction-to-wcf/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>
