<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.codeville.net/~d/styles/itemcontent.css"?><!-- generator="wordpress/2.3" --><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Steve Sanderson's blog</title>
	<link>http://blog.stevensanderson.com</link>
	<description>Now with less downtime</description>
	<pubDate>Mon, 12 Jul 2010 08:49:13 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.3</generator>
	<language>en</language>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.codeville.net/SteveCodeville" /><feedburner:info uri="stevecodeville" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Editing a variable-length list, Knockout-style</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/Csa56G35woU/</link>
		<comments>http://blog.stevensanderson.com/2010/07/12/editing-a-variable-length-list-knockout-style/#comments</comments>
		<pubDate>Mon, 12 Jul 2010 08:34:48 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[Knockout]]></category>

		<guid isPermaLink="false">http://blog.stevensanderson.com/2010/07/12/editing-a-variable-length-list-knockout-style/</guid>
		<description><![CDATA[Following my previous blog post about Knockout, a JavaScript UI library that provides a nice structure for building responsive web UIs with a similar programming model to Silverlight, a few people have asked to see an “editable grid”-type example. There’s a read-only paging grid example here, but what about editing and validating?
Previously I wrote about [...]]]></description>
			<content:encoded><![CDATA[<p align="left">Following my previous blog post about <a href="http://blog.stevensanderson.com/?p=254" target="_blank">Knockout</a>, a JavaScript UI library that provides a nice structure for building responsive web UIs with a similar programming model to Silverlight, a few people have asked to see an “editable grid”-type example. There’s a read-only paging grid example <a href="http://knockoutjs.com/examples/grid.html" target="_blank">here</a>, but what about editing and validating?</p>
<p>Previously I wrote about <a href="http://blog.stevensanderson.com/2010/01/28/validating-a-variable-length-list-aspnet-mvc-2-style/" target="_blank">editing and validating variable-length lists with ASP.NET MVC 2</a>, and before that <a href="http://blog.stevensanderson.com/2008/12/22/editing-a-variable-length-list-of-items-in-aspnet-mvc/" target="_blank">with ASP.NET MVC 1</a>. Those demos were OK, but it’s way easier with Knockout – it eliminates the most of the complex moving parts and the fiddly client-server interaction, the precise element naming requirements, and the hackery needed to make validation work.</p>
<p align="center"><em>Note: Knockout works with any server-side web development framework,      <br />but this blog post focuses on using it with ASP.NET MVC</em></p>
<h4>Live demo</h4>
<p>Before we get into the code, see what we’re about to build. It’s simple, but nice to use. Try it out in this live IFRAME:</p>
<p>  <iframe style="width:620px; height: 300px;" src="http://demo.stevensanderson.com/ko_gift_editor/"></iframe><br />
<small>Note: Some RSS readers will strip out the preceding IFRAME. If you don&#8217;t see the live demo, see <a href="http://blog.stevensanderson.com/2010/07/12/editing-a-variable-length-list-knockout-style/">this post on the web</a> instead.</small></p>
<p>Right, how’s it done?</p>
<h4>Sending some initial state down to the client</h4>
<p>First, define a C# model for the data items we’re editing:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> <span style="color: #0000FF;">class</span> GiftModel 
<span style="color: #000000;">&#123;</span> 
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">string</span> Title <span style="color: #000000;">&#123;</span> get; set; <span style="color: #000000;">&#125;</span> 
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">double</span> Price <span style="color: #000000;">&#123;</span> get; set; <span style="color: #000000;">&#125;</span> 
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Next, create an action method that renders a view, passing some GiftModel instances to it:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> ActionResult Index<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> 
<span style="color: #000000;">&#123;</span> 
    <span style="color: #0000FF;">var</span> initialState = <span style="color: #0000FF;">new</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#123;</span> 
        <span style="color: #0000FF;">new</span> GiftModel <span style="color: #000000;">&#123;</span> Title = <span style="color: #A31515;">&quot;Tall Hat&quot;</span>, Price = <span style="color: #000000;">49.95</span> <span style="color: #000000;">&#125;</span>, 
        <span style="color: #0000FF;">new</span> GiftModel <span style="color: #000000;">&#123;</span> Title = <span style="color: #A31515;">&quot;Long Cloak&quot;</span>, Price = <span style="color: #000000;">78.25</span> <span style="color: #000000;">&#125;</span> 
    <span style="color: #000000;">&#125;</span>; 
    <span style="color: #0000FF;">return</span> View<span style="color: #000000;">&#40;</span>initialState<span style="color: #000000;">&#41;</span>; 
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>… and then, in the view, convert that C# model data into a JavaScript object:</p>

<div class="wp_syntax"><div class="code"><pre class="text">&lt;script type=&quot;text/javascript&quot;&gt; 
    var initialData = &lt;%= new JavaScriptSerializer().Serialize(Model) %&gt;; 
&lt;/script&gt;</pre></div></div>

<h4>Creating a Client-side View Model</h4>
<p>Right now our view model only needs one property – gifts – which will be an observable array of gift items. Once we’ve got that, we can tell Knockout to bind this to any HTML nodes that request binding:</p>

<div class="wp_syntax"><div class="code"><pre class="text">var viewModel = { 
    gifts : ko.observableArray(initialData)
}; 
&nbsp;
ko.applyBindings(document.body, viewModel);</pre></div></div>

<p>To check this is all working, let’s just bind a SPAN’s text content to the length of the observable array:</p>

<div class="wp_syntax"><div class="code"><pre class="text">&lt;p&gt;You have asked for &lt;span data-bind=&quot;text: gifts().length&quot;&gt;&amp;nbsp;&lt;/span&gt; gift(s)&lt;/p&gt;</pre></div></div>

<p>Because <strong>gifts</strong> is an <em>observable</em> array, the text in this SPAN will be updated automatically whenever the length of the array changes. With all this in place, you should now see the following:</p>
<p><a href="http://blog.stevensanderson.com/wp-content/uploads/2010/07/image.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://blog.stevensanderson.com/wp-content/uploads/2010/07/image-thumb.png" width="449" height="265" /></a>&#160;</p>
<h4>Making an editable grid</h4>
<p>Making data editable is a matter of creating HTML input controls and binding them to that data, and the easiest way to create repeated blocks of markup is to use a template. So, here’s how to make a table containing an editor row for each gift item:</p>

<div class="wp_syntax"><div class="code"><pre class="text">&lt;table&gt; 
    &lt;tbody data-bind=&quot;template: { name: 'giftRowTemplate', foreach: gifts }&quot;&gt;&lt;/tbody&gt; 
&lt;/table&gt;
&nbsp;
&lt;script type=&quot;text/html&quot; id=&quot;giftRowTemplate&quot;&gt; 
    &lt;tr&gt; 
        &lt;td&gt;Gift name: &lt;input data-bind=&quot;value: Title&quot;/&gt;&lt;/td&gt; 
        &lt;td&gt;Price: \$ &lt;input data-bind=&quot;value: Price&quot;/&gt;&lt;/td&gt; 
    &lt;/tr&gt; 
&lt;/script&gt;</pre></div></div>

<p>This will produce the following output:</p>
<p><a href="http://blog.stevensanderson.com/wp-content/uploads/2010/07/image5.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://blog.stevensanderson.com/wp-content/uploads/2010/07/image-thumb1.png" width="587" height="298" /></a> </p>
<p>Now, if you edit the contents of the text boxes, it will actually edit the underlying data model. You can’t really see any effect of that just yet, but you will be able to when we save the data.</p>
<h4>Adding gifts</h4>
<p>Adding items just means adding them to the <strong>gifts</strong> observable array in the underlying view model; the UI will take care of updating itself. So, create a button that triggers an ‘add’ method on the view model:</p>

<div class="wp_syntax"><div class="code"><pre class="text">&lt;button data-bind=&quot;click: addGift&quot;&gt;Add Gift&lt;/button&gt;</pre></div></div>

<p>… and then implement such a method, pushing a new blank item into the array:</p>

<div class="wp_syntax"><div class="code"><pre class="text">var viewModel = {
&nbsp;
    // ... leave the rest as before ...
    addGift: function () { 
        this.gifts.push({ Title: &quot;&quot;, Price: &quot;&quot; }); 
    }
&nbsp;
};</pre></div></div>

<p>That does it.</p>
<h4>Removing gifts</h4>
<p>Again, you only need to edit the underlying array. So, edit the giftRowTemplate and put a ‘Delete’ link on each row:</p>

<div class="wp_syntax"><div class="code"><pre class="text">&lt;script type=&quot;text/html&quot; id=&quot;giftRowTemplate&quot;&gt; 
    &lt;tr&gt; 
        &lt;!-- Leave the rest as before --&gt; 
        &lt;td&gt;&lt;a href=&quot;#&quot; data-bind=&quot;click: function() { viewModel.removeGift($data) }&quot;&gt;Delete&lt;/a&gt;&lt;/td&gt; 
    &lt;/tr&gt; 
&lt;/script&gt;</pre></div></div>

<p>… and implement a removeGift method on the view model:</p>

<div class="wp_syntax"><div class="code"><pre class="text">var viewModel = { 
    // ... leave the rest as before ...
&nbsp;
    removeGift: function (gift) { 
        this.gifts.remove(gift); 
    }
&nbsp;
};</pre></div></div>

<p>Now, when you click ‘delete’ on any item, it will vanish from both the underlying data model and the HTML UI.</p>
<h4>Saving data (i.e., submitting it back to the server)</h4>
<p>Since we’re following the MVVM pattern, all our really important data is in the view model – the view (the HTML UI) is merely a representation of that. So, we don’t want to submit data from the view by doing a regular form post. Instead, we want to submit the state of the view model as this may contain more data than is visible to the user.</p>
<p>First, we need to know when the user wants to save their data. To do this, we can wrap up our UI inside a regular HTML &lt;form&gt; with a submit button, and then bind the ‘submit’ event to a method on the view model. (Doing it this way preserves familiar behaviours like pressing “Enter” to submit a form)</p>

<div class="wp_syntax"><div class="code"><pre class="text">&lt;form class=&quot;giftListEditor&quot; data-bind=&quot;submit: save&quot;&gt;
    &lt;!-- Our other UI elements, including the table and ‘add’ button, go here --&gt; 
&nbsp;
    &lt;button data-bind=&quot;enable: gifts().length &gt; 0&quot; type=&quot;submit&quot;&gt;Submit&lt;/button&gt; 
&lt;/form&gt;</pre></div></div>

<p>Notice that I’ve made the “submit” button enabled only when there’s at least one item. Next, add a ‘save’ method that packages up the view model state as JSON and posts it to the server:</p>

<div class="wp_syntax"><div class="code"><pre class="text">var viewModel = {
&nbsp;
    // ... leave the rest as before ...
    save: function() { 
        ko.utils.postJson(location.href, { gifts: this.gifts }); 
    } 
};</pre></div></div>

<p>It would be perfectly easy to submit the data via Ajax using jQuery’s $.post or $.ajax methods, but I’ve chosen to use postJson (a utility function inside Knockout) to send the data as a regular HTML form submission instead. That means the server-side code doesn’t have to know anything about Ajax and can imagine you’re posting a normal HTML form. As I said, Ajax works fine too – I’m just demonstrating another option here. </p>
<p>The view model posts the data to the same URL you’re already on (i.e., location.href) because that’s ASP.NET MVC’s convention. To collect the data on the server, add an action method as follows:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #000000;">&#91;</span>HttpPost<span style="color: #000000;">&#93;</span> 
<span style="color: #0000FF;">public</span> ActionResult Index<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#91;</span>FromJson<span style="color: #000000;">&#93;</span> IEnumerable&lt;GiftModel&gt; gifts<span style="color: #000000;">&#41;</span> 
<span style="color: #000000;">&#123;</span> 
    <span style="color: #008000;">// Can process the data any way we want here, </span>
    <span style="color: #008000;">// e.g., further server-side validation, save to database, etc </span>
    <span style="color: #0000FF;">return</span> View<span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;Saved&quot;</span>, gifts<span style="color: #000000;">&#41;</span>; 
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>That’s pretty easy! This fits into ASP.NET MVC’s usual data-entry conventions – the server-side code is totally trivial. It doesn’t use ASP.NET MVC’s usual data binding mechanism so you don’t have to worry about element naming, field prefixes, and all that; instead, the data is packaged as JSON and deserialized using [FromJson]. I’ll omit the source code to [FromJson] for now, but it’s totally general-purpose, only about 10 lines long, and is included in the downloadable example with this blog post.</p>
<p>The server-side code can now do whatever it wants. For this example, I’m just rendering a different view to show what data the server received.</p>
<h4>Adding Validation</h4>
<p>Right now, somebody could enter a text string for “Price”, and then this will cause a deserialization error on the server. This is an abomination, and must be stopped! Let’s add some client-side validation. </p>
<p>Knockout works nicely with any client-side validation framework that can cope with you dynamically modifying the DOM. jQuery.Validation copes perfectly with that, so let’s use it. Having referenced jquery.validate.js, define rules by putting special CSS classes on the elements in the template. (Note that jQuery.Validation lets you define custom rule logic in this way, too.)</p>

<div class="wp_syntax"><div class="code"><pre class="text">&lt;script type=&quot;text/html&quot; id=&quot;giftRowTemplate&quot;&gt; 
    &lt;tr&gt; 
        &lt;td&gt;Gift name: &lt;input class=&quot;required&quot; data-bind=&quot;value: Title, uniqueName: true&quot;/&gt;&lt;/td&gt; 
        &lt;td&gt;Price: \$ &lt;input class=&quot;required number&quot; data-bind=&quot;value: Price, uniqueName: true&quot;/&gt;&lt;/td&gt; 
        &lt;td&gt;&lt;a href=&quot;#&quot; data-bind=&quot;click: function() { viewModel.removeGift($data) }&quot;&gt;Delete&lt;/a&gt;&lt;/td&gt; 
    &lt;/tr&gt; 
&lt;/script&gt;</pre></div></div>

<p>Notice the “required” and “number” classes. One other thing to bear in mind is that, although Knockout doesn’t need your bound elements to have names or IDs, jQuery.Validation does depend on every validated element having a unique name. That’s why I’ve put <strong>uniqueName:true</strong> into the bindings. This is a trivial binding I added that just checks whether the element has a name, and if not, gives it a unique one. An easy workaround for the jQuery.Validation limitation.</p>
<p>Next, remove the “<strong>submit</strong>” binding from the form, and tell jQuery.Validation to catch the form’s <strong>submit</strong> event instead, and to call our view model’s <strong>save</strong> method only if the form is valid:</p>

<div class="wp_syntax"><div class="code"><pre class="text">$(&quot;form&quot;).validate({ submitHandler: function() { viewModel.save() } });</pre></div></div>

<p>That’s it! Now the user can’t submit blank fields, nor can they submit text for the “Price” fields. They can still add and remove items, though, and this doesn’t affect the state of the validation feedback for other rows in the table.</p>
<p>Of course you can still validate the data on the server, too – and you need to if blank data would actually violate your business rules in some important way. Typically I’d recommend putting such logic into your domain layer, to ensure the rules are always respected no matter what UI technology (ASP.NET MVC, Knockout, Silverlight, an iPhone app) is connected to it. To display any errors, you can use something like an ASP.NET MVC “ValidationSummary” helper. (Or you can just throw an exception and give up if it looks like the user is deliberately bypassing client-side validation – it’s up to you.)</p>
<p>There’s plenty more I could describe here, such as how to use bindings to add animated transitions (e.g., applying jQuery’s fadeIn or slideUp when users add or remove items), but I think this is enough for now.</p>
<h4>Questions and support</h4>
<p>I’ve had plenty of questions about how to do things with Knockout since my blog post last week. To capture these discussions and make them public, I’ve made a Google Group for Knockout at <a href="http://groups.google.com/group/knockoutjs">http://groups.google.com/group/knockoutjs</a> – please use this for general questions about the framework. However if you have comments about the particular example shown in this post, go ahead and post them here on this blog.</p>
<p>If you want to play with the gift list editor code a little more, <a href="http://blog.stevensanderson.com/blogfiles/2010/July/koListEditor.zip" target="_blank">download the demo project</a>.</p>
<div class="feedflare">
<a href="http://feeds.codeville.net/~ff/SteveCodeville?a=Csa56G35woU:bfwp-EtCIAQ:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?i=Csa56G35woU:bfwp-EtCIAQ:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=Csa56G35woU:bfwp-EtCIAQ:G79ilh31hkQ"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?d=G79ilh31hkQ" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=Csa56G35woU:bfwp-EtCIAQ:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?i=Csa56G35woU:bfwp-EtCIAQ:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=Csa56G35woU:bfwp-EtCIAQ:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/SteveCodeville/~4/Csa56G35woU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.stevensanderson.com/2010/07/12/editing-a-variable-length-list-knockout-style/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.stevensanderson.com/2010/07/12/editing-a-variable-length-list-knockout-style/</feedburner:origLink></item>
		<item>
		<title>Introducing Knockout, a UI library for JavaScript</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/7kGUt8ah6kI/</link>
		<comments>http://blog.stevensanderson.com/2010/07/05/introducing-knockout-a-ui-library-for-javascript/#comments</comments>
		<pubDate>Mon, 05 Jul 2010 17:27:10 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[Javascript]]></category>

		<category><![CDATA[Knockout]]></category>

		<category><![CDATA[UI]]></category>

		<guid isPermaLink="false">http://blog.stevensanderson.com/2010/07/05/introducing-knockout-a-ui-library-for-javascript/</guid>
		<description><![CDATA[Knockout is a 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.
So, what distinguishes [...]]]></description>
			<content:encoded><![CDATA[<p><strong><a href="http://knockoutjs.com">Knockout</a></strong> is a JavaScript library that makes it easier to create rich, desktop-like user interfaces with JavaScript and HTML, using <em>observers </em>to make your UI automatically stay in sync with an underlying data model. It works particularly well with the MVVM pattern, offering <em>declarative bindings </em>somewhat like Silverlight but without the browser plugin.</p>
<p>So, what distinguishes this from all the other similar-sounding JavaScript libraries? (I blogged about an MVC/templating system for JavaScript <a href="http://blog.stevensanderson.com/2007/10/18/jmvcnet-neat-client-side-mvc-for-aspnet/" target="_blank">back in 2007</a>, Microsoft has suggested a <a href="http://wiki.github.com/nje/jquery-datalink/jquery-data-linking-proposal" target="_blank">data linking system</a> for jQuery, and Google’s full of <a href="http://www.google.co.uk/search?hl=en&amp;q=javascript+mvc" target="_blank">MVC-on-the-client</a> toolkits.) </p>
<p>Well, Knockout combines some different ideas that open up very powerful possibilities:</p>
<ul>
<li><strong>Automatic dependency tracking:</strong> At the heart of Knockout is a system of observable variables and other variables computed as functions of them. For example, if you have <strong>firstName</strong> and <strong>lastName</strong> and then define <strong>fullName</strong> by concatenating these together, the framework knows that whenever either <strong>firstName</strong> or <strong>lastName</strong> changes, it must re-evaluate <strong>fullName</strong>. You don’t have to configure this – it’s inferred from your code execution, even if you have chains of observables referencing other observables.       <br />This makes it easy to build sophisticated view models in which changes to a few key properties automatically ripple out to all other affected parts of the model.       </li>
<li><strong>Declarative bindings:</strong> By adding a <strong>data-*</strong> attribute (part of the HTML 5 spec, and works fine in older browsers, including IE 6) you can quickly bind appearance and behaviour in your HTML to properties on a view model. For example, you can write <strong>&lt;span data-bind=&quot;text: fullName&quot;&gt;&lt;/span&gt;</strong>, and then the element will display the value in your model property as text, automatically updating if any of the underlying data changes. Besides <strong>text</strong>, I’ve included a range of commonly useful declarative bindings (e.g., <strong>visible</strong>, <strong>click</strong>, and <strong>css</strong>), and you can easily plug in custom ones.       </li>
<li><strong>Nested templates:</strong> When you have a rich structure of view model data to display, it makes sense to display it using a template to keep your code simple. Knockout handles this easily by letting you bind a DOM node to a template and some data. Whenever either changes, the template gets re-rendered and your UI is updated. You can use <strong>data-bind</strong> attributes from inside templates (referencing any variable in scope at that point during template execution, such as <strong>foreach</strong> loop variables) to concisely add further interactivity. Plus, you can bind to templates from within templates, creating chains of nested templates. Because of how dependency tracking works, if the underlying data changes, Knockout knows it only needs to re-render the innermost templates affected by the change, so it’s efficient. Knockout uses the <a href="http://wiki.github.com/nje/jquery/jquery-templates-proposal" target="_blank">jquery-tmpl</a> template engine by default, but you can plug in another template engine if you prefer some other template syntax. </li>
</ul>
<p>These features together, combined with following the MVVM design pattern, mean you can apply sophisticated UI behaviours in a clean, concise, and organized way. It’s also possible to combine custom bindings and templates to create reusable controls (or <em>plugins</em>).</p>
<h4>Extremely Trivial Example</h4>
<p>OK, code. You could set up a view model as follows:</p>

<div class="wp_syntax"><div class="code"><pre class="text">&lt;script type=&quot;text/javascript&quot;&gt;
    var myViewModel = {
        personName : ko.observable(&quot;Bert&quot;) // Initial state
    };
&lt;/script&gt;</pre></div></div>

<p>Then, you could bind it to an HTML UI as follows:</p>

<div class="wp_syntax"><div class="code"><pre class="text">Enter your name:
&lt;input id=&quot;source&quot; data-bind=&quot;value: personName, valueUpdate: 'keyup'&quot; /&gt;
&nbsp;
&lt;div data-bind=&quot;visible: personName().length &gt; 5&quot;&gt;
    Wow, what a long name you have.
&lt;/div&gt;</pre></div></div>

<p>Now, the text box will take its value from personName, and will automatically update its value whenever personName changes. The binding is two-way, so when you type into the text box, this updates personName. </p>
<p>The DIV with the “what a long name” message will be made visible whenever the name length exceeds 5 characters, and hidden otherwise. By referencing an observable value in a binding, you’ve implicitly set up notifications.</p>
<h4>But I can just do that with jQuery!</h4>
<p>Yes, we all love jQuery! It’s a fantastic replacement for the hideous DOM API we had to work with before.</p>
<p>The point of Knockout is not to replace jQuery – I expect most people who use Knockout will use jQuery too. The point is to make it easy to have one coherent underlying data model and then bind your UI to that. Change the data model and the UI changes, and vice-versa. That way, you don’t get complicated event handlers that have to update loads of different parts of the DOM to keep the UI up-to-date; instead, when you just change the underlying data model, you know all the affected UI gets updated. This also makes client-server interactions much easier: when saving data, you don’t have to try to scrape the current state off a load of DOM elements – you’ve already got it in a clean model. Likewise when loading data from the server and wanting to update the DOM to match – just push it into the data model and the UI is updated. It’s the MVVM pattern, much beloved of Silverlight developers.</p>
<h4>A More Detailed Tutorial</h4>
<p>Right, getting beyond “hello world” but still keeping things simple, let’s make a simple list editor. This will demonstrate some of Knockout’s core features – observables and bindings (though we’ll ignore templating for now – you can learn about that from other examples). </p>
<p>To get started, create an HTML file that references <strong>knockout.js</strong> or <strong>knockout-min.js</strong> and define a simple view model class. In JavaScript, any function can act as a class constructor. The following one has a single property which represents the items in a list.</p>

<div class="wp_syntax"><div class="code"><pre class="text">&lt;html&gt;
&lt;head&gt;
    &lt;script type=&quot;text/javascript&quot; src=&quot;knockout.js&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;	
    &lt;script type=&quot;text/javascript&quot;&gt;
        var listEditorViewModel = function () {
            // ko.observableArray lets you track changes to a collection of things
            this.allItems = ko.observableArray([&quot;Apple&quot;, &quot;Banana&quot;, &quot;Cherry&quot;]);
        };
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</pre></div></div>

<p>Next, let’s display the list on the screen. You can do that by creating an HTML &lt;select&gt; element and binding its contents to a model property using Knockout’s options binding:</p>

<div class="wp_syntax"><div class="code"><pre class="text">&lt;div&gt;List items:&lt;/div&gt;
&lt;select multiple=&quot;multiple&quot; data-bind=&quot;options: allItems&quot;&gt;&lt;/select&gt;</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="text">&lt;script type=&quot;text/javascript&quot;&gt;
    var listEditorViewModel = function () {
        ... as before ...
    };
&nbsp;
    ko.applyBindings(document.body, new listEditorViewModel());
&lt;/script&gt;</pre></div></div>

<p>If you open this in a browser, you’ll see the list items:</p>
<p><a href="http://blog.stevensanderson.com/wp-content/uploads/2010/07/image1.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image1" border="0" alt="image1" src="http://blog.stevensanderson.com/wp-content/uploads/2010/07/image1-thumb.png" width="549" height="224" /></a>&#160; </p>
<p>What about letting the user add some more items to the list? Update the view model class so that it has another property for tracking the new item a user is adding, and add a method that pushes the new item into the array:</p>

<div class="wp_syntax"><div class="code"><pre class="text">var listEditorViewModel = function () {
    // ko.observableArray lets you track changes to a collection of things
    this.allItems = ko.observableArray([&quot;Apple&quot;, &quot;Banana&quot;, &quot;Cherry&quot;]);
&nbsp;
    // ko.observable tracks a single item. The initial state here is an empty string.
    this.itemToAdd = ko.observable(&quot;&quot;);
&nbsp;
    this.addItem = function () {
        this.allItems.push(this.itemToAdd());
        this.itemToAdd(&quot;&quot;); // After adding an item, reset itemToAdd to an empty string 
    }
};</pre></div></div>

<p>Next we need to add some UI elements and bind them to these new model members. </p>

<div class="wp_syntax"><div class="code"><pre class="text">&lt;form data-bind=&quot;submit: addItem&quot;&gt;
    Add item:
    &lt;input data-bind=&quot;value: itemToAdd&quot; /&gt;
    &lt;button type=&quot;submit&quot;&gt;Add&lt;/button&gt;
&lt;/form&gt;</pre></div></div>

<p>That will do it! Now when the user edits the text box, its value automatically goes into the <strong>itemToAdd</strong> observable because of the <strong>value</strong> binding. When they submit the form, this invokes <strong>addItem()</strong> because of the <strong>submit</strong> binding. In turn, this updates <strong>allItems</strong> in the view model, and this automatically causes the on-screen list to be updated because its collection of options is bound to that model property. With Knockout, you don’t have to remember which parts of the UI to update following an event – you just change properties on the underlying view model, and anything bound to those properties will be notified and updated.</p>
<p><a href="http://blog.stevensanderson.com/wp-content/uploads/2010/07/image2.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image2" border="0" alt="image2" src="http://blog.stevensanderson.com/wp-content/uploads/2010/07/image2-thumb.png" width="620" height="266" /></a> </p>
<p>Next thing, we might want to let the user remove items. We should let them select multiple items at once, then have a “remove” button that removes them all. First, we need to know what the user has got selected, so add a new view model property to represent selection, and bind it to the HTML element using Knockout’s <strong>selectedOptions</strong> binding.</p>

<div class="wp_syntax"><div class="code"><pre class="text">&lt;select multiple data-bind=&quot;options: allItems, selectedOptions: selectedItems&quot;&gt;&lt;/select&gt;</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="text">var listEditorViewModel = function () {
    // ... leave the rest as before ...
    this.selectedItems = ko.observableArray([]); // Initially select nothing
};</pre></div></div>

<p>Now you can read <b>selectedItems</b> to see what items are selected, and if you write a value to that observable, it will change what’s selected in the UI.</p>
<p>To let the user remove their selected items, add a button and bind clicks on it to a method on the view model:</p>

<div class="wp_syntax"><div class="code"><pre class="text">&lt;button data-bind=&quot;click: removeSelected&quot;&gt;
    Remove selected items
&lt;/button&gt;</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="text">var listEditorViewModel = function () {
    // ... leave the rest as before ...
&nbsp;
    this.removeSelected = function () {
        this.allItems.removeAll(this.selectedItems());
        this.selectedItems([]); // Reset selection to an empty set
    }
};</pre></div></div>

<p>That’s great – now the user can remove one or more items from the list. But it doesn’t make sense for them to click “Remove selected items” if they haven’t got anything selected. Let’s make the button enabled only when at least one item is selected:</p>

<div class="wp_syntax"><div class="code"><pre class="text">&lt;button data-bind=&quot;click: removeSelected, enable: selectedItems().length &gt; 0&quot;&gt;
    Remove selected items
&lt;/button&gt;</pre></div></div>

<p>Easy! You can use arbitrary JavaScript expressions in bindings. If your bindings reference one or more observables, they’ll be re-evaluated automatically any time those observables change. So now the “Remove” button becomes enabled or disabled depending on whether anything is selected.</p>
<p><a href="http://blog.stevensanderson.com/wp-content/uploads/2010/07/image3.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image3" border="0" alt="image3" src="http://blog.stevensanderson.com/wp-content/uploads/2010/07/image3-thumb.png" width="600" height="290" /></a> </p>
<p>What if you wanted to let the user sort the items into alphabetical order? Again, you could do this by adding a method to the view model and binding a new button to that method. Alternatively – just to show you that you can use function literals in bindings – here’s a standalone way to do it:</p>

<div class="wp_syntax"><div class="code"><pre class="text">&lt;button data-bind=&quot;click: function() { allItems.sort() }, enable: allItems().length &gt; 1&quot;&gt;
    Sort
&lt;/button&gt;</pre></div></div>

<p>I’ve made this button enable only when there are at least two items (it’s pointless to “sort” a single item). Notice that selection is retained, because we didn’t change <strong>selectedItems</strong>.</p>
<p><a href="http://blog.stevensanderson.com/wp-content/uploads/2010/07/image4.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image4" border="0" alt="image4" src="http://blog.stevensanderson.com/wp-content/uploads/2010/07/image4-thumb.png" width="620" height="298" /></a> </p>
<p>That’s a fair bit of functionality in just a few lines of code. As I explained earlier, the benefit of Knockout and the MVVM pattern is that it scales very well in complexity – you don’t have to track how one part of the UI affects another; you just manipulate your view model and all affected parts of the UI change on their own. For example, in the preceding tutorial, removing items can make the ‘Sort’ button become disabled, but we didn’t have to write any explicit code in a ‘Remove’ click handler to make that happen. </p>
<p>To build on this knowledge, see the <a href="http://knockoutjs.com/examples/">online demos of other examples</a> (arranged in order of increasing sophistication) and look at their HTML source code to see how it’s done.</p>
<h4>Requirements, Licensing, and Browser Support</h4>
<p>Knockout is written in pure JavaScript, so it has no server-side requirements at all. Your web application can be written in ASP.NET MVC, PHP, Ruby on Rails – whatever.</p>
<p>The core of Knockout doesn’t depend on any other JavaScript library. However, the default template engine, jquery-tmpl, obviously depends on jQuery. If you don’t like that you can plug in another template engine, but I expect most people will be using jQuery anyway.</p>
<p>Regarding browser support, I’ve designed and tested it to work with IE 6 – 8, Firefox 2 – 3.6, and current versions of Chrome, Safari (verified on Windows and iPhone), and Opera. I fully expect it to work with older versions of Chrome, Safari, and Opera, but haven’t tried it – there’s only so much browser installation one person can bear&#8230; There’s a good set of automated specifications (BDD-style, written using JSSpec) so you can run these on any browser/platform to get a good sense of what features are working. Hopefully all of them <img src='http://blog.stevensanderson.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>I’m releasing this project under the Ms-Pl license (an OSI-approved license). Some of my other code is licensed in the same way, so this keeps things simple for me, and it means you can use the library in any commercial or non-commercial project.</p>
<h4>Where do I go from here?</h4>
<p>For more details, examples, source, and downloads, see the project&#8217;s homepage at <a href="http://knockoutjs.com">http://knockoutjs.com</a></p>
<div class="feedflare">
<a href="http://feeds.codeville.net/~ff/SteveCodeville?a=7kGUt8ah6kI:jVG22PsbrnQ:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?i=7kGUt8ah6kI:jVG22PsbrnQ:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=7kGUt8ah6kI:jVG22PsbrnQ:G79ilh31hkQ"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?d=G79ilh31hkQ" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=7kGUt8ah6kI:jVG22PsbrnQ:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?i=7kGUt8ah6kI:jVG22PsbrnQ:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=7kGUt8ah6kI:jVG22PsbrnQ:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/SteveCodeville/~4/7kGUt8ah6kI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.stevensanderson.com/2010/07/05/introducing-knockout-a-ui-library-for-javascript/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.stevensanderson.com/2010/07/05/introducing-knockout-a-ui-library-for-javascript/</feedburner:origLink></item>
		<item>
		<title>Pro ASP.NET MVC 2 Framework</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/-jVRCAmMXxs/</link>
		<comments>http://blog.stevensanderson.com/2010/06/11/pro-aspnet-mvc-2-framework/#comments</comments>
		<pubDate>Fri, 11 Jun 2010 10:15:57 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[ASP.NET]]></category>

		<category><![CDATA[MVC]]></category>

		<category><![CDATA[Pro ASP.NET MVC]]></category>

		<guid isPermaLink="false">http://blog.stevensanderson.com/2010/06/11/pro-aspnet-mvc-2-framework/</guid>
		<description><![CDATA[This week Apress is sending the second edition of my ASP.NET MVC book to the printers. Hopefully this means you can get your hands on physical copies by the end of this month.
The first edition went deep into the details of the MVC Framework, providing both tutorials and reference material. Judging by sales and review [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.amazon.com/gp/product/1430228865?ie=UTF8&amp;tag=stesansblo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=1430228865" target="_blank"><img style="border-bottom: 0px; border-left: 0px; margin: 0px 0px 0px 5px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" align="right" src="http://blog.stevensanderson.com/wp-content/uploads/2010/06/image.png" width="211" height="263" /></a>This week Apress is sending the second edition of my ASP.NET MVC book to the printers. Hopefully this means you can get your hands on physical copies by the end of this month.</p>
<p>The first edition went deep into the details of the MVC Framework, providing both tutorials and reference material. Judging by sales and review scores, it was a success. The second edition:</p>
<ul>
<li>… is thoroughly updated for <strong>ASP.NET MVC 2</strong>. It explains all the new features, including templating, metadata, validation, asynchronous controllers, areas, HTTP method overloading, strongly-typed input helpers, default parameters, etc., and many are demonstrated in the various tutorials.</li>
<li>… is updated to account for <strong>.NET 4</strong> and <strong>Visual Studio 2010</strong>. Even though .NET 4/C# 4 is the preferred technology throughout the book, all the documentation and code accounts for readers using .NET 3.5 as well.</li>
<li>… is updated to reflect more <strong>recent patterns and best practices</strong>. For example, discussions of automated testing apply ideas from Behaviour Driven Development (BDD) where relevant, and tutorials and descriptions now consistently distinguish between view models and domain models.</li>
<li>… is updated in light of <strong>reader feedback</strong> from the first edition. Certain explanations and terminology are overhauled, and the tutorials make use of more effective third-party libraries (e.g., Ninject for Dependency Injection).</li>
</ul>
<p>This blog post is partly intended to build awareness of the new book, and is partly intended to deal with some of the questions I regularly get by email. So, here are some questions that people frequently ask:</p>
<h4></h4>
<h4>Is this a new book, or an update?</h4>
<p>It’s an update of the first edition. The following diagram should clarify what proportions of the book are new, dramatically changed, or just refreshed:</p>
<p><a href="http://blog.stevensanderson.com/wp-content/uploads/2010/06/image1.png"><img style="border-bottom: 0px; border-left: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px" title="image" border="0" alt="image" src="http://blog.stevensanderson.com/wp-content/uploads/2010/06/image-thumb.png" width="517" height="145" /></a></p>
<h4>Where and <em>exactly</em> when can I get it?</h4>
<p>I don’t know the exact date when it will ship; this depends on physical production and distribution schedules that are beyond my knowledge.</p>
<ul>
<li>For printed copies, your best bet is to <a href="http://www.amazon.com/gp/product/1430228865?ie=UTF8&amp;tag=stesansblo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=1430228865" target="_blank">pre-order with Amazon</a>. Hopefully these will ship around the end of June, but I can’t guarantee it.</li>
<li>For the eBook version, keep checking the <a href="http://www.apress.com/book/view/1430228865" target="_blank">Apress web site</a>.</li>
</ul>
<p>There’ll probably be a Kindle version in due course, too.</p>
<h4>If I already have the first edition, should I buy the second edition?</h4>
<p>If you use ASP.NET MVC regularly - especially if plan to use the new MVC 2 features but haven’t yet learned about them in depth - you may well get a lot out of reading the new edition and seeing what’s the same and what’s new. You may also have colleagues who need a deeper knowledge of the whole MVC Framework, including both v1 and v2 features.</p>
<p>However if you don’t use ASP.NET MVC much and don’t intend to migrate your development to v2, perhaps there isn’t such a strong case for buying an update of a book you already own.</p>
<p>Some readers have asked if they can get a sort of “upgrade” edition which contains only the new material. That wouldn’t really make sense for this book, as the new concepts and practices are applied throughout. I don’t present “old” material followed by “new” material – the whole manuscript is updated as a single coherent guide to ASP.NET MVC 2 from the beginning as I believe this gives the clearest understanding.</p>
<h4>What new and updated in the second edition?</h4>
<p>There are far too many updates and enhancements in the new edition to describe them all. Here’s a brief outline of the table of contents and roughly how each chapter has changed.</p>
<h5>Chapter 1: What’s the Big Idea?</h5>
<p>Updated to account for ASP.NET 4, including improvements to WebForms and how this impacts the comparison between the two frameworks. Gives an overview of what’s new in ASP.NET MVC 2. Changed the discussion general software development practices to account for more recent trends. </p>
<h5>Chapter 2: Your First ASP.NET MVC Application</h5>
<p>Tutorial now accounts for your choice of Visual Studio 2008 or Visual Studio 2010. Uses new ASP.NET MVC 2 features, including empty project template, automatic HTML encoding, and Data Annotations validation. Streamlined the flow of the tutorial to improve readability.</p>
<h5>Chapter 3: Prerequisites</h5>
<p>Describes newer architectural patterns including MVVM. Discussion of automated testing expanded to cover integration testing as well as unit testing, and demonstrates Cucumber-style BDD testing and explains the tradeoffs between this and traditional unit TDD. Various updates to terminology and explanations.</p>
<h4></h4>
<h5>Chapter 4, 5, 6: SportsStore tutorial </h5>
<p>Now accounts for your choice of Visual Studio 2008 or Visual Studio 2010. Improved the code: better project structure, uses Ninject instead of Castle Windsor for DI, has better unit test naming (BDD-style) with a clearer description of the limitations of such testing. Applies the viewmodel pattern and related terminology more consistently. </p>
<p>Adapted the tutorial to benefit from MVC 2 features including optional parameters, metadata, scaffolding, client-side validation, automatic (de)serialization, etc. Some parts of the tutorial now go in a different order to make it easier to follow.</p>
<h5>Chapter 7: Overview of ASP.NET MVC Projects</h5>
<p>Updated to account for ASP.NET MVC 2’s two project template options (empty and non-empty), and for changes in the core ASP.NET 4 platform regarding configuration and deployment.</p>
<h5>Chapter 8: URLs and Routing</h5>
<p>Now covers areas – reasons for using them, setting them up, their impact on routing, how to avoid common problems, how to unit test their routing configuration. Explains how .NET 4 changes where the routing code lives and how ASP.NET MVC 2 deals with controller namespaces. Many smaller changes.</p>
<h5>Chapter 9: Controllers</h5>
<p>The 1st edition’s “Controllers” chapter is now split in two – this first chapter now covers introductory topics – receiving input data with parameter binding etc, producing output with action results etc., unit testing. </p>
<p>Has many changes to account for ASP.NET MVC 2, such as its enhancements to TempData. Also describes .NET 4 features – using optional parameters (and how these differ from ASP.NET MVC 2’s parameter defaults), using “dynamic” as a model type, etc. Expands the coverage of unit testing, demonstrating 5 ways to make mocking controllers easier.</p>
<h5>Chapter 10: Controller Extensibility</h5>
<p>The 1st edition’s “Controllers” chapter is now split in two – this second chapter now covers more advanced topics – custom filters, method selectors, controller factories, etc. </p>
<p>Updated to reflect changes in the ASP.NET MVC 2 request-processing pipeline, new built-in filters, HTTP Method Overriding, etc. Adds (a lot of) coverage of asynchronous controllers – not just how to use them, but how to measure their impact and avoid common misconfiguration problems.</p>
<h5>Chapter 11: Views</h5>
<p>Goes into detail about how automatic HTML encoding works. Coverage of HTML helper methods expanded for ASP.NET MVC 2 (there’s now over 50 helpers, and that’s before you even start counting all their different overloads). Explains new ways to render partials.</p>
<h5>Chapter 12: Models</h5>
<p>Most of this massive chapter is totally new, and goes into great detail about metadata, templating, and validation. Covers how the built-in templates work, creating custom ones, using HTML field prefixes, implementing custom metadata sources, consuming metadata, custom validation providers, custom client-side validation, doing all this inside a multi-tier architecture, etc.</p>
<p>The explanation of model binding and value providers is significantly updated to account for the new architecture in ASP.NET MVC 2.</p>
<h5>Chapter 13: User Interface Techniques</h5>
<p>This new chapter inherits UI-related material from various parts of the 1st edition book, including wizards, CAPTCHAs, child actions, master pages, open-source view engines, custom view engines. All updated to match ASP.NET MVC 2, of course.</p>
<h5>Chapter 14: Ajax and Client Scripting</h5>
<p>Updated various aspects of the code and explanations to account for new framework features, and to make things work with more recent versions of IE. Expanded the coverage of JSON data services, including security issues and ways to handle cross-domain requests. Some recommendations are updated to account for client-side performance considerations(browser’s rendering pipeline, CDNs, etc). </p>
<h5>Chapter 15: Security and Vulnerability</h5>
<p>Mostly the same as in the first edition. Shows an alternative tamper-proofing mechanism using MVC 2 code, plus describes JavaScript string encoding and its relation to script injection. Various code changes to fit in with ASP.NET MVC 2. </p>
<h5>Chapter 16: Deployment</h5>
<p>Radically restructured chapter – now all organized with step-by-step guides and checklists for each targeted IIS version, so now you only have to read the material relevant to you. Covers new deployment options, including combinations of .NET 3.5 SP1, .NET 4, Server 2003, Server 2008, Server 2008 R2, Server 2008 R2 Core, shared hosting, classic/integrated pipeline mode, etc. Accounts for many changes to these deployment environments since the 1st edition, including IIS 7.5-specific issues </p>
<p>Clearer explanations of various IIS request-processing mechanisms. A new section describes VS2010’s improved publishing and packaging mechanisms, config file transforms, etc. </p>
<h5>Chapter 17: Using ASP.NET Core Platform Features</h5>
<p>Mostly the same as in the first edition. Updated to account for ASP.NET MVC 2, IIS 7.5, with tweaks to code and explanations. Information about configuration APIs moved from Deployment chapter into this chapter.</p>
<h5>Chapter 18: Migrating Existing Applications to ASP.NET MVC 2.0</h5>
<p>Various updates relating to .NET 4 / VS2010 / ASP.NET MVC 2, including how to upgrade Web Forms applications to support MVC, using routing when combining MVC with Web Forms (both on .NET 3.5 and .NET 4), ways you can use Web Forms server controls with postbacks in MVC 2, should you wish to.</p>
<p>New section describes upgrading from ASP.NET MVC 1 – using automated tooling, doing it manually, a post-upgrade checklist, workarounds for potential problems.</p>
<h4>OK, enough details</h4>
<p>Of course, there are <a href="http://www.amazon.com/s/?search-alias=aps&amp;field-keywords=mvc%202" target="_blank">other ASP.NET MVC 2 books in the pipeline too</a>. No doubt you’ll enjoy and benefit from any of them.</p>
<div class="feedflare">
<a href="http://feeds.codeville.net/~ff/SteveCodeville?a=-jVRCAmMXxs:R1elqtO5qrM:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?i=-jVRCAmMXxs:R1elqtO5qrM:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=-jVRCAmMXxs:R1elqtO5qrM:G79ilh31hkQ"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?d=G79ilh31hkQ" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=-jVRCAmMXxs:R1elqtO5qrM:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?i=-jVRCAmMXxs:R1elqtO5qrM:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=-jVRCAmMXxs:R1elqtO5qrM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/SteveCodeville/~4/-jVRCAmMXxs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.stevensanderson.com/2010/06/11/pro-aspnet-mvc-2-framework/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.stevensanderson.com/2010/06/11/pro-aspnet-mvc-2-framework/</feedburner:origLink></item>
		<item>
		<title>Using HtmlUnit on .NET for Headless Browser Automation</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/CFpn76VhqFI/</link>
		<comments>http://blog.stevensanderson.com/2010/03/30/using-htmlunit-on-net-for-headless-browser-automation/#comments</comments>
		<pubDate>Tue, 30 Mar 2010 10:33:05 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[BDD]]></category>

		<category><![CDATA[Testing]]></category>

		<category><![CDATA[UI]]></category>

		<guid isPermaLink="false">http://blog.stevensanderson.com/2010/03/30/using-htmlunit-on-net-for-headless-browser-automation/</guid>
		<description><![CDATA[If you subscribe to this blog, you may have noticed that I’ve been writing about test automation methods a lot lately. You could even think of it as a series covering different technical approaches:

Hosting your app in a real web server and testing it through a real web browser using WatiN (plus, in this case, [...]]]></description>
			<content:encoded><![CDATA[<p>If you subscribe to this blog, you may have noticed that I’ve been writing about test automation methods a lot lately. You could even think of it as a series covering different technical approaches:</p>
<ul>
<li><a href="/2010/03/03/behavior-driven-development-bdd-with-specflow-and-aspnet-mvc/" target="_blank">Hosting your app in a real web server and testing it through a real web browser</a> using WatiN (plus, in this case, SpecFlow for Cucumber-style specifications)</li>
<li><a href="/2009/03/27/first-steps-with-lightweight-test-automation-framework/" target="_blank">Hosting your app in a real web server and testing it with client-side automation</a> using Microsoft’s Lightweight Test Automation Framework</li>
<li><a href="/2009/06/11/integration-testing-your-aspnet-mvc-application/" target="_blank">Hosting your app directly in the test suite process and bypassing both the web server and the browser entirely</a> using my MvcIntegrationTestFramework experiment</li>
<li>Unit testing code in isolation – <a href="/2009/08/24/writing-great-unit-tests-best-and-worst-practises/" target="_blank">best and worst practices</a>, and <a href="/2009/11/04/selective-unit-testing-costs-and-benefits/" target="_blank">why I think unit testing isn’t applicable to all types of code</a></li>
<li><a href="/2010/03/09/deleporter-cross-process-code-injection-for-aspnet/" target="_blank">Injecting code across process boundaries</a> to assist integration testing approaches that host your app in a real web server, using Deleporter</li>
</ul>
<p>The reason I keep writing about this is that I still think it’s very much an unsolved problem. We all want to deliver more reliable software, we want better ways to design functionality and verify implementation… but we don’t want to get so caught up in the beaurocracy of test suite maintenance that it consumes all our time and obliterates productivity. </p>
<h4>Yet another approach</h4>
<p>Rails developers (and to a lesser extent Java web developers) commonly use yet another test automation technique: <strong>hosting the app in a real web server, and accessing it through a fast, invisible, simulated web browser</strong> rather than a real browser. This is known as <em>headless browser automation</em>. </p>
<p>How is this beneficial?</p>
<ul>
<li><strong>It’s faster than driving a real browser.</strong> The simulated browser is just a native code library, so it’s very quick to launch and shut down, doesn’t require interprocess communication with your test suite, and doesn’t waste time physically drawing things on your screen, opening and closing pop-up windows, etc. Nonetheless, the simulated browser is full-featured: it exposes the usual HTML DOM API, runs JavaScript, evaluates CSS rules, and so on, so it’s still an effective way to specify rich client-side behaviours.</li>
<li><strong>It’s more reliable than a real browser.</strong> Real browsers are complicated. For example, if you launch and shut down Firefox many times in rapid succession, occasionally it will fail to launch because a previous instance is still locking some file. Simulated browsers are totally independent, so don’t suffer these kinds of weirdness.</li>
<li><strong>You can get more low-level control if you want it.</strong> For example, the simulated browser can easily offer an API to alter the HTTP headers it sends, or let you get or set the contents of its cache. A real browser wouldn’t usually make this easy.</li>
</ul>
<p>And what drawbacks might you expect?</p>
<ul>
<li><strong>It can be harder to debug.</strong> Because you can’t physically see the browser on your desktop, it’s not as obvious what’s happening if a test fails (or passes) unexpectedly. Your debugger’s “immediate mode” will let you call the browser’s API to figure things out, but it can be a longer investigative process.</li>
<li><strong>There’s no absolute guarantee that it faithfully replicates a real-world browser.</strong> For example, HtmlUnit can simulate multiple versions of Firefox, Internet Explorer, and Netscape, but it may not simulate every single quirk.</li>
</ul>
<h4>About HtmlUnit</h4>
<p>HtmlUnit is a headless browser automation library for Java. It’s very well-developed and mature, as you can see from its <a href="http://htmlunit.sourceforge.net/apidocs/index.html" target="_blank">extensive API</a>. (Need to configure whether the user has JavaScript on or off? <a href="http://htmlunit.sourceforge.net/apidocs/com/gargoylesoftware/htmlunit/WebClient.html#setJavaScriptEnabled(boolean)" target="_blank">No problem</a>.) It’s also the same technology that underlies <a href="http://celerity.rubyforge.org/" target="_blank">Celerity</a>, a Ruby library that exposes the Watir API but runs faster.</p>
<p>Unfortunately, in .NET world, we don’t have any good headless browser automation libraries like HtmlUnit that I know of. But don’t let that stop you! We do have <a href="http://www.ikvm.net/" target="_blank">IKVM</a> – a near-magic way of running Java code on .NET (either by hosting a JVM on the CLR at runtime, or by a one-time conversion process that generates a native .NET assembly directly from the Java bytecode). So, why not use HtmlUnit itself?</p>
<h4>Converting HtmlUnit to .NET</h4>
<p>It’s surprisingly easy to get HtmlUnit, a Java library, converted into a native .NET assembly (no Java Virtual Machine needed!) using IKVM. </p>
<p>First, <a href="http://htmlunit.sourceforge.net/" target="_blank">download HtmlUnit (as a compiled JAR file) from SourceForge</a> (I’m using version 2.7), and extract all its files from the ZIP archive.</p>
<p>Second, <a href="http://www.ikvm.net/" target="_blank">download IKVM binaries from ikvm.net/SourceForge</a> (I’m using version 0.42.0.3), and again extract all its files from the ZIP archive.</p>
<p>Open a command prompt, ensure you’ve added IKVM’s <strong>/bin</strong> folder to your PATH variable, change directory to HtmlUnit’s <strong>/lib</strong> folder, and then run <strong>ikvmc</strong> to convert the Java bytecode of all of the HtmlUnit JAR files into .NET bytecode. I ran this command:</p>
<pre>ikvmc -out:htmlunit-2.7.dll *.jar</pre>
<p>This produced a lot of warnings and a large (~10Mb) .NET assembly called <strong>htmlunit-2.7.dll</strong>. If you don’t want to bother with this process, you can download my sample project (linked below) which contains the .NET assembly I generated.</p>
<h4>Using HtmlUnit from .NET </h4>
<p>Once you’ve got <strong>htmlunit-2.7.dll</strong> as a .NET assembly, you can use it with any .NET unit testing library such as NUnit or XUnit. You will also need to reference a few of the IKVM runtime assemblies (I narrowed it down to six additional IKVM assemblies that appear to be needed – these are all included in IKVM’s <strong>/bin</strong> folder).</p>
<p>As a trivial example, here’s how you can use HtmlUnit with NUnit to load the Google homepage:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #000000;">&#91;</span>TestFixture<span style="color: #000000;">&#93;</span>
<span style="color: #0000FF;">public</span> <span style="color: #0000FF;">class</span> GoogleTests
<span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">private</span> WebClient webClient;
    <span style="color: #000000;">&#91;</span>SetUp<span style="color: #000000;">&#93;</span> <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">void</span> Setup<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span> webClient = <span style="color: #0000FF;">new</span> WebClient<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #000000;">&#91;</span>Test<span style="color: #000000;">&#93;</span>
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">void</span> Can_Load_Google_Homepage<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0000FF;">var</span> page = <span style="color: #000000;">&#40;</span>HtmlPage<span style="color: #000000;">&#41;</span>webClient.<span style="color: #0000FF;">getPage</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;http://www.google.com&quot;</span><span style="color: #000000;">&#41;</span>;
        Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;Google&quot;</span>, page.<span style="color: #0000FF;">getTitleText</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Slightly more interesting, here’s how you can fill out a form (again, Google Search), click a button, and inspect the results:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #000000;">&#91;</span>Test<span style="color: #000000;">&#93;</span>
<span style="color: #0000FF;">public</span> <span style="color: #0000FF;">void</span> Google_Search_For_AspNetMvc_Yields_Link_To_Codeplex<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">var</span> searchPage = <span style="color: #000000;">&#40;</span>HtmlPage<span style="color: #000000;">&#41;</span>webClient.<span style="color: #0000FF;">getPage</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;http://www.google.com&quot;</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>HtmlInput<span style="color: #000000;">&#41;</span>searchPage.<span style="color: #0000FF;">getElementByName</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;q&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">setValueAttribute</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;asp.net mvc&quot;</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #0000FF;">var</span> resultsPage = <span style="color: #000000;">&#40;</span>HtmlPage<span style="color: #000000;">&#41;</span>searchPage.<span style="color: #0000FF;">getElementByName</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;btnG&quot;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">click</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
    <span style="color: #0000FF;">var</span> linksToCodeplex = <span style="color: #0000FF;">from</span> tag <span style="color: #0000FF;">in</span> resultsPage.<span style="color: #0000FF;">getElementsByTagName</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;a&quot;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">toArray</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Cast</span>&lt;HtmlAnchor&gt;<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
                          let href = tag.<span style="color: #0000FF;">getHrefAttribute</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
                          <span style="color: #0000FF;">where</span> href.<span style="color: #0000FF;">StartsWith</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;http://&quot;</span><span style="color: #000000;">&#41;</span>
                          let uri = <span style="color: #0000FF;">new</span> Uri<span style="color: #000000;">&#40;</span>href<span style="color: #000000;">&#41;</span>
                          <span style="color: #0000FF;">where</span> uri.<span style="color: #0000FF;">Host</span>.<span style="color: #0000FF;">ToLower</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">EndsWith</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;codeplex.com&quot;</span><span style="color: #000000;">&#41;</span>
                          <span style="color: #0000FF;">select</span> uri;
    CollectionAssert.<span style="color: #0000FF;">IsNotEmpty</span><span style="color: #000000;">&#40;</span>linksToCodeplex<span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>As you can see, the API is full of Java idioms and feels a bit odd to a .NET developer. It would be great if someone decided to create a .NET wrapper library to expose a nicer API, .NET-style PascalCase, better use of IEnumerable and generics so LINQ queries were simpler, etc.</p>
<p>The other side of it is that HtmlUnit is very powerful. You can trivially scan the DOM with XPath, search for child elements, invoke events, much more easily than with WatiN.</p>
<p>To show that HtmlUnit has great JavaScript and Ajax support, here’s an example of automating a jQuery AutoComplete plugin to check its suggestions:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #000000;">&#91;</span>Test<span style="color: #000000;">&#93;</span>
<span style="color: #0000FF;">public</span> <span style="color: #0000FF;">void</span> jQuery_Autocomplete_Lon_Suggests_London<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #008000;">// Arrange: Load the demo page</span>
    <span style="color: #0000FF;">var</span> autocompleteDemoPage = <span style="color: #000000;">&#40;</span>HtmlPage<span style="color: #000000;">&#41;</span>webClient.<span style="color: #0000FF;">getPage</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;http://jquery.bassistance.de/autocomplete/demo/&quot;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
    <span style="color: #008000;">// Act: Type &quot;lon&quot; into the input box</span>
    autocompleteDemoPage.<span style="color: #0000FF;">getElementById</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;suggest1&quot;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">type</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;lon&quot;</span><span style="color: #000000;">&#41;</span>;
    webClient.<span style="color: #0000FF;">waitForBackgroundJavaScript</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">1000</span><span style="color: #000000;">&#41;</span>;
&nbsp;
    <span style="color: #008000;">// Assert: Suggestions should include &quot;London&quot;</span>
    <span style="color: #0000FF;">var</span> suggestions = autocompleteDemoPage.<span style="color: #0000FF;">getByXPath</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;//div[@class='ac_results']/ul/li&quot;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">toArray</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Cast</span>&lt;HtmlElement&gt;<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Select</span><span style="color: #000000;">&#40;</span>x =&gt; x.<span style="color: #0000FF;">asText</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
    CollectionAssert.<span style="color: #0000FF;">Contains</span><span style="color: #000000;">&#40;</span>suggestions, <span style="color: #A31515;">&quot;London&quot;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>In case you want to download all this code as a demo project you can run without needing IKVM or Java or anything weird, <a href="http://github.com/SteveSanderson/HtmlUnit_DemoOnDotNet" target="_blank">I’ve put it on GitHub</a>.</p>
<h4>Summary</h4>
<p>This is experimental! I haven’t used this on any real project, though it was pretty effortless so far, so I’d definitely consider it. I don’t know how much faster HtmlUnit would be than a real browser, but it does bypass the trickiness of real browsers, which may be worth it alone. If I was going to use it seriously, I’d definitely make some .NET wrapper classes to hide the Java naming and idioms. HtmlUnit on .NET feels robust, but I haven’t pushed it hard.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fblog.stevensanderson.com%2f2010%2f03%2f30%2fusing-htmlunit-on-net-for-headless-browser-automation%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fblog.stevensanderson.com%2f2010%2f03%2f30%2fusing-htmlunit-on-net-for-headless-browser-automation%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<div class="feedflare">
<a href="http://feeds.codeville.net/~ff/SteveCodeville?a=CFpn76VhqFI:i8Xim1RyyjU:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?i=CFpn76VhqFI:i8Xim1RyyjU:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=CFpn76VhqFI:i8Xim1RyyjU:G79ilh31hkQ"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?d=G79ilh31hkQ" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=CFpn76VhqFI:i8Xim1RyyjU:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?i=CFpn76VhqFI:i8Xim1RyyjU:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=CFpn76VhqFI:i8Xim1RyyjU:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/SteveCodeville/~4/CFpn76VhqFI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.stevensanderson.com/2010/03/30/using-htmlunit-on-net-for-headless-browser-automation/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.stevensanderson.com/2010/03/30/using-htmlunit-on-net-for-headless-browser-automation/</feedburner:origLink></item>
		<item>
		<title>Deleporter: Cross-Process Code Injection for ASP.NET</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/wPRRvC2cibQ/</link>
		<comments>http://blog.stevensanderson.com/2010/03/09/deleporter-cross-process-code-injection-for-aspnet/#comments</comments>
		<pubDate>Tue, 09 Mar 2010 21:52:06 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[ASP.NET]]></category>

		<category><![CDATA[BDD]]></category>

		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://blog.stevensanderson.com/2010/03/09/deleporter-cross-process-code-injection-for-aspnet/</guid>
		<description><![CDATA[Deleporter is a little .NET library that teleports arbitrary delegates into an ASP.NET application in some other process (e.g., hosted in IIS) and runs them there. At the moment, it’s still pretty experimental, but I’ve found it useful so far.
Why would you want this? It’s mainly useful when you’re integration testing. Normally, integration tests can’t [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://github.com/SteveSanderson/Deleporter" target="_blank">Deleporter</a> is a little .NET library that teleports arbitrary delegates into an ASP.NET application in some other process (e.g., hosted in IIS) and runs them there. At the moment, it’s still pretty experimental, but I’ve found it useful so far.</p>
<p>Why would you want this? It’s mainly useful when you’re <a href="http://blog.stevensanderson.com/?p=239" target="_blank">integration testing</a>. Normally, integration tests can’t directly interact with your application’s code because it’s in a separate process (and possibly running on another machine). So, unlike unit tests, integration tests often struggle to test different configurations and have no option to use mocks.</p>
<p>Deleporter gets around that limitation. It lets you delve into a remote ASP.NET application’s internals without any special cooperation from the remote app (it just needs to include an extra IHttpModule in its config), and then you can do any of the following:</p>
<ul>
<li><strong>Cross-process mocking</strong>, by combining it with any mocking tool. For example, you could inject a temporary mock database or simulate the passing of time (e.g., if your integration tests want to specify what happens after 30 days or whatever)</li>
<li><strong>Test different configurations</strong>, by writing to static properties in the remote ASP.NET appdomain or using the ConfigurationManager API to edit its &lt;appSettings&gt; entries.</li>
<li><strong>Run teardown or cleanup logic</strong> such as flushing caches. For example,&#160; recently I needed to restore a SQL database to a known state after each test in the suite. The trouble was that ASP.NET connection pool was still holding open connections on the old database, causing connection errors. I resolved this easily by using Deleporter to issue a <em>SqlConnection.ClearAllPools()</em> command in the remote appdomain – the ASP.NET app under test didn’t need to know anything about it.</li>
</ul>
<p>Rails developers can already do this either by hosting their app in-process (e.g., with <a href="http://wiki.github.com/brynary/webrat/" target="_blank">WebRat</a>) or using <a href="http://github.com/ngty/cross-stub" target="_blank">a cross-process mocking tool</a>. I’ve already talked about <a href="http://blog.stevensanderson.com/2009/06/11/integration-testing-your-aspnet-mvc-application/" target="_blank">hosting ASP.NET (MVC) apps in-process with integration tests</a> (the starting point for this code); now I wanted to get the same benefits while hosting my app on a real web server.</p>
<p>This library is built on regular .NET remoting. But unlike regular remoting, it run arbitrary delegates, not just methods specifically exposed by the remoting service. If the code for your delegate isn’t already loaded into the ASP.NET appdomain, Deleporter will serialize the code and send it across. This is really essential for being useful from an integration test suite, because the test code wouldn’t normally be in the real app. </p>
<h4>Enough talk! Code now.</h4>
<p>To use it, first download <a href="http://github.com/SteveSanderson/Deleporter/downloads" target="_blank">the binary</a> or compile <a href="http://github.com/SteveSanderson/Deleporter" target="_blank">the source</a> to get Deleporter.dll. Reference it from both your integration test project <em>and</em> the ASP.NET MVC/WebForms app you’re testing. </p>
<p>Next, to get your ASP.NET app to listen for commands, edit its Web.config file to reference this extra HTTP module:</p>

<div class="wp_syntax"><div class="code"><pre class="xml"><span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;configuration<span style="font-weight: bold; color: black;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;system</span>.web<span style="font-weight: bold; color: black;">&gt;</span></span>
    <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;httpModules<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #808080; font-style: italic;">&lt;!-- If you're using Visual Studio's built-in web server, or IIS 5 or 6, add this: --&gt;</span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;add</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;DeleporterServerModule&quot;</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;DeleporterCore.Server.DeleporterServerModule, Deleporter&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
    <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/httpModules<span style="font-weight: bold; color: black;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/system</span>.web<span style="font-weight: bold; color: black;">&gt;</span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;system</span>.webServer<span style="font-weight: bold; color: black;">&gt;</span></span>
    <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;modules<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #808080; font-style: italic;">&lt;!-- If you're using IIS 7+, add this: --&gt;</span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;add</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;DeleporterServerModule&quot;</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;DeleporterCore.Server.DeleporterServerModule, Deleporter&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
    <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/modules<span style="font-weight: bold; color: black;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/system</span>.webServer<span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/configuration<span style="font-weight: bold; color: black;">&gt;</span></span></span></pre></div></div>

<p>Now, when you next start up your ASP.NET app, it will listen on TCP port 38473 - a randomly-chosen default - for commands from your integration test suite. </p>
<p>In your integration test code, you can now run arbitrary delegates in the remote ASP.NET app, sending both data and code into it, and optionally pulling data back. As a trivial example, you can pull back the server’s time local time:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #000000;">&#91;</span>Test<span style="color: #000000;">&#93;</span>
<span style="color: #0000FF;">public</span> <span style="color: #0000FF;">void</span> ServerClockHasCorrectYear<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    DateTime serverTime = Deleporter.<span style="color: #0000FF;">Run</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> =&gt; DateTime.<span style="color: #0000FF;">Now</span><span style="color: #000000;">&#41;</span>;
    Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>DateTime.<span style="color: #0000FF;">Now</span>.<span style="color: #0000FF;">Year</span>, serverTime.<span style="color: #0000FF;">Year</span>, <span style="color: #A31515;">&quot;The server's clock is way off&quot;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>You can use multi-statement lambdas, too, even if they capture locals from the containing method. Deleporter will send the captured locals into the remote app (as long as they&#8217;re serializable), and if the remote app edits them, it will pull back the new values and update your locals. In other words, anonymous methods and multi-statement lambdas work with captured local variables just as if all the code was running locally. Example:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #000000;">&#91;</span>Test<span style="color: #000000;">&#93;</span>
<span style="color: #0000FF;">public</span> <span style="color: #0000FF;">void</span> SendingAndUpdatingCapturedLocals<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    DateTime serverTime = <span style="color: #0000FF;">default</span><span style="color: #000000;">&#40;</span>DateTime<span style="color: #000000;">&#41;</span>;
    <span style="color: #0000FF;">string</span> fileToLocate = <span style="color: #A31515;">&quot;~/web.config&quot;</span>;
    <span style="color: #0000FF;">string</span> mappedPhysicalPath = <span style="color: #0000FF;">null</span>;
&nbsp;
    Deleporter.<span style="color: #0000FF;">Run</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> =&gt; <span style="color: #000000;">&#123;</span>
        <span style="color: #008000;">// This code, which both reads and writes locals from the outer scope,</span>
        <span style="color: #008000;">// runs in the remote ASP.NET application</span>
        serverTime = DateTime.<span style="color: #0000FF;">Now</span>;
        mappedPhysicalPath = HostingEnvironment.<span style="color: #0000FF;">MapPath</span><span style="color: #000000;">&#40;</span>fileToLocate<span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
    Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>DateTime.<span style="color: #0000FF;">Now</span>.<span style="color: #0000FF;">Year</span>, serverTime.<span style="color: #0000FF;">Year</span><span style="color: #000000;">&#41;</span>;
    Assert.<span style="color: #0000FF;">IsTrue</span><span style="color: #000000;">&#40;</span>File.<span style="color: #0000FF;">Exists</span><span style="color: #000000;">&#40;</span>mappedPhysicalPath<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>; <span style="color: #008000;">// Of course, this will only be true if the ASP.NET app runs on the same machine as the integration test code</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<h4>More realistic applications</h4>
<p>So far I’ve only shown very artificial examples designed to illustrate the syntax. To give you a more realistic idea of how you could apply it, I can offer two sample applications.</p>
<ul>
<li><a href="http://github.com/SteveSanderson/Deleporter/tree/master/Samples/" target="_blank">A very simple ASP.NET MVC app called <em>WhatTimeIsIt</em></a> whose sole behaviour varies according to the date. Like all good ASP.NET MVC applications, it uses the <em>Dependency Injection </em>pattern (in this example, with Ninject) to get the current date &amp; time from an IDateProvider – the default implementation of which just returns DateTime.Now.
<div style="margin-top:1em">
It has simple integration tests that use Deleporter and Moq to inject a mock IDateProvider across the process boundary while the app is running, and then verifies some behaviour that only happens during specific dates. It also demonstrates an easy way of tidying up after the tests run (restoring the original IDateProvider) automatically without cluttering the test code with teardown logic.
</div>
<div style="margin-top:1em">
Here’s how the cross-process mocking works:
</div>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #008000;">// Inject a mock IDateProvider, setting the clock back to 1975</span>
<span style="color: #0000FF;">var</span> dateToSimulate = <span style="color: #0000FF;">new</span> DateTime<span style="color: #000000;">&#40;</span><span style="color: #000000;">1975</span>, <span style="color: #000000;">1</span>, <span style="color: #000000;">1</span><span style="color: #000000;">&#41;</span>;
Deleporter.<span style="color: #0000FF;">Run</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> =&gt; <span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">var</span> mockDateProvider = <span style="color: #0000FF;">new</span> Mock&lt;IDateProvider&gt;<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
    mockDateProvider.<span style="color: #0000FF;">Setup</span><span style="color: #000000;">&#40;</span>x =&gt; x.<span style="color: #0000FF;">CurrentDate</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Returns</span><span style="color: #000000;">&#40;</span>dateToSimulate<span style="color: #000000;">&#41;</span>;
    NinjectControllerFactoryUtils.<span style="color: #0000FF;">TemporarilyReplaceBinding</span><span style="color: #000000;">&#40;</span>mockDateProvider.<span style="color: #0000FF;">Object</span><span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>;</pre></div></div>

</li>
<li><a href="http://github.com/SteveSanderson/GuestbookDemo" target="_blank">An enhanced version of the SpecFlow BDD-style integration test suite</a> from my previous blog post. It now uses Deleporter to apply a mock repository to verify certain specifications.
<div style="margin-top:1em">
For example, one of the Gherkin files now specifies this scenario:
</div>

<div class="wp_syntax"><div class="code"><pre>Scenario: Most recent entries are displayed first
	Given we have the following existing entries
		| Name      | Comment      | Posted date       |
		| Mr. A     | I like A     | 2008-10-01 09:20  |
		| Mrs. B    | I like B     | 2010-03-05 02:15  |
		| Dr. C     | I like C     | 2010-02-20 12:21  |
      And I am on the guestbook page
    Then the guestbook entries includes the following, in this order
		| Name      | Comment      | Posted date       |
		| Mrs. B    | I like B     | 2010-03-05 02:15  |
		| Dr. C     | I like C     | 2010-02-20 12:21  |
		| Mr. A     | I like A     | 2008-10-01 09:20  |</pre></div></div>

</li>
</ul>
<h4>Gotcha: What you must remember to avoid confusing problems</h4>
<p>One behaviour might surprise you at first. It’s certainly caught me out plenty of times already. Each time you edit and recompile your integration test code, you must also recycle your ASP.NET appdomain (e.g., by resaving its Web.config file, or the nuclear option - running <em>iisreset</em>) otherwise the old code will still be loaded into it. That’s because, as far as I’m aware, there’s no way to unload an assembly from a .NET appdomain. Once your delegates have been transferred over, they’re staying there and can’t automatically be replaced by newer versions.</p>
<p>This isn’t a problem if you’re running an integration suite through your continuous integration (CI) system – the app code would be recompiled and hence reset between test suite runs. It’s only something to watch out for during local development. In the Deleporter.Test.Client project I’ve shown a crude but working way of automatically recycling the ASP.NET appdomain when the test suite starts running; you may be able to work out a better way of automating this if you need one.</p>
<h4>Important security note</h4>
<p><strong>You should not enable DeleporterServerModule on a production web site.</strong> It’s only supposed to be used in dev and QA environments, because it’s literally an invitation to upload and execute arbitrary code.</p>
<p>To reduce the chance of a mistake, DeleporterServerModule will refuse to run if your web site was compiled in release mode – it will demand that you remove the IHttpModule from your Web.config file. Technically you should be OK if your firewall doesn’t accept inbound connections on port 38473 (or whatever port you configure it to listen on) anyway. Obviously, no warranties, you use it at your own risk, etc.</p>
<p>License: Ms-Pl</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fblog.stevensanderson.com%2f2010%2f03%2f09%2fdeleporter-cross-process-code-injection-for-aspnet"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fblog.stevensanderson.com%2f2010%2f03%2f09%2fdeleporter-cross-process-code-injection-for-aspnet" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<div class="feedflare">
<a href="http://feeds.codeville.net/~ff/SteveCodeville?a=wPRRvC2cibQ:XCax283o42w:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?i=wPRRvC2cibQ:XCax283o42w:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=wPRRvC2cibQ:XCax283o42w:G79ilh31hkQ"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?d=G79ilh31hkQ" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=wPRRvC2cibQ:XCax283o42w:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?i=wPRRvC2cibQ:XCax283o42w:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=wPRRvC2cibQ:XCax283o42w:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/SteveCodeville/~4/wPRRvC2cibQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.stevensanderson.com/2010/03/09/deleporter-cross-process-code-injection-for-aspnet/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.stevensanderson.com/2010/03/09/deleporter-cross-process-code-injection-for-aspnet/</feedburner:origLink></item>
		<item>
		<title>Behavior Driven Development (BDD) with SpecFlow and ASP.NET MVC</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/RBNm3XN1ERw/</link>
		<comments>http://blog.stevensanderson.com/2010/03/03/behavior-driven-development-bdd-with-specflow-and-aspnet-mvc/#comments</comments>
		<pubDate>Wed, 03 Mar 2010 10:14:54 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[Agile]]></category>

		<category><![CDATA[BDD]]></category>

		<category><![CDATA[Development process]]></category>

		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://blog.stevensanderson.com/2010/03/03/behavior-driven-development-bdd-with-specflow-and-aspnet-mvc/</guid>
		<description><![CDATA[Test Driven Development (TDD) has been around for about a decade, and has been mainstream for at least five years now. During this time, TDD practitioners have been gradually changing and refining the methodology, the mindset, and the terminology in an effort to increase its usefulness and avoid some of the problems that newcomers often [...]]]></description>
			<content:encoded><![CDATA[<p>Test Driven Development (TDD) has been around for about a decade, and has been mainstream for at least five years now. During this time, TDD practitioners have been gradually changing and refining the methodology, the mindset, and the terminology in an effort to increase its usefulness and avoid some of the problems that newcomers often experience.
</p>
<p>The mindset and terminology has shifted so much that some folks have started using a new name for the updated methodology: BDD. Here’s a brief overview*:</p>
<ul>
<li><strong>Test Driven Development </strong>seeks to improve software quality by getting you to follow an iterative workflow often called <a href="http://geekswithblogs.net/WillSmith/archive/2008/03/18/red-green-refactor.aspx" target="_blank">red-green-refactor</a>. In theory, it keeps quality high because if any change breaks earlier functionality, you should be notified by way of a failing test. Also, it should help you to make more pragmatic decisions about what code to write, because you only write the simplest code needed to make all your tests pass.
<div style="margin:1em 0 1em 0">
Despite its unfortunate name, it became clear over time that TDD’s greatest potential benefit is not as a technique for testing code or detecting bugs, but in fact as a code design aid, because it provides a precise mechanism for specifying how your code should behave before you get mentally caught up in the actual implementation. However, in reality, I’ve seen many developers still struggle to break free from a test-oriented mindset and continue to amass reams of unit tests that simply exercise every possible code path without usefully describing what this proves or why it represents correct behaviour. This doesn’t aid design, very rarely detects bugs, and yet consumes a huge amount of maintenance time.
</div>
</li>
<li><strong>Behaviour Driven Development</strong> retains the basic red-green workflow, but dramatically puts the emphasis on specifying behaviours that are understandable to people (often, business domain experts). It addresses questions such as “How much should I specify?” and “How should I organise and name my specifications so they are most useful?”
<div style="margin:1em 0 1em 0">
To do this, BDD says you should elevate your mind to a level of behavioural abstraction above the code implementation. So don’t say “Constructor_Test” or even&#160; “Constructor_NullParam _ThrowsArgumentNullException” but instead say “A shipment cannot be created without a recipient address”. The change of emphasis and terminology leads people to write more useful specifications.
</div>
<div style="margin:1em 0 1em 0">
I won’t focus on the term BDD itself, because the term is not hugely useful: nobody has ever given it a precise definition as far as I’m aware, and there isn’t a lot of consensus about what it should mean (some say it should only be about the UI; others say not). Instead, in this blog post, I’m going to focus on the major tools that have come out of the BDD stable and the advantages they can give you.
</div>
</li>
</ul>
<h5>Unit level or UI level?</h5>
<p>You can write BDD-style specifications about <em>individual code units</em>, in which case you’ll&#160; probably use a context/specification style framework like <a href="http://rspec.info/" target="_blank">RSpec</a> (for Ruby) or in .NET something like <a href="http://codebetter.com/blogs/aaron.jensen/archive/2008/05/08/introducing-machine-specifications-or-mspec-for-short.aspx" target="_blank">MSpec</a> or <a href="http://code.google.com/p/specunit-net/" target="_blank">SpecUnit</a> (personally, I don’t like either). Unit-level specifications work brilliantly for most code that ultimately exposes an API for other code. But personally, I spend most of my time writing UI code, usually with ASP.NET MVC, and UI code is fundamentally different. It isn’t about producing an API – it’s about producing user experience (UX) behaviours. These behaviours typically aren’t atomic (contained within a single click or HTTP request); their essence exists only across a sequence of interactions. As such, unit-level specifications can fall short and fail to capture the UI behaviours you have in mind. I wrote before about <a href="http://blog.stevensanderson.com/2009/11/04/selective-unit-testing-costs-and-benefits/" target="_blank">why, in real projects, I’ve found unit tests to be of limited value for ASP.NET MVC controllers</a>. </p>
<p>Alternatively, you can write BDD-style specifications about <em>UI interactions</em>. Assuming you’re building a web application, you’ll probably use a browser automation library like WatiR/WatiN or Selenium, and script it either using one of the frameworks I just mentioned, or a <em>given/when/then</em> tool such as <a href="http://cukes.info/" target="_blank">Cucumber</a> (for Ruby) or <a href="http://specflow.org/" target="_blank">SpecFlow</a> (for .NET). In this blog post, I’ll describe these tools and provide an example based on ASP.NET MVC.</p>
<p><small><em>* I don’t claim to be an authority on BDD, so if you think I’ve got this all wrong, I invite you to come along and tell me what I’ve misunderstood. Try to be specific, please. My existing understanding is based on having done a lot of TDD, seeing its limitations especially in large teams, and recognising that some of these BDD ideas look like they could help with that.</em></small></p>
<h4>So, what’s Cucumber?</h4>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="image" border="0" alt="image" align="right" src="http://blog.stevensanderson.com/wp-content/uploads/2010/03/image-thumb.png" width="240" height="78" /> <a href="http://cukes.info/" target="_blank">Cucumber</a> is a Ruby tool that offers a natural-language way to specify behaviours in terms of “Given, When, Then” (GWT) sentence fragments. This language is called <em>Gherkin.</em> You create a plain-text file (called a “.feature” file) containing a set of scenario definitions written in Gherkin, for example</p>
<pre>
Scenario: Show logged in user name
  Given I am logged in as a user called "Steve"
   When I visit the homepage
   Then the page header displays the caption "Hello, Steve!"
</pre>
<p>… and also provide Ruby scripts that define what the runner should do when it hits matching steps, for example</p>

<div class="wp_syntax"><div class="code"><pre class="ruby">Given /I am logged <span style="color:#9966CC; font-weight:bold;">in</span> as a user called <span style="color:#996600;">&quot;(.*)&quot;</span>/ <span style="color:#9966CC; font-weight:bold;">do</span> |name|
    create_user<span style="color:#006600; font-weight:bold;">&#40;</span>name<span style="color:#006600; font-weight:bold;">&#41;</span>
    sign_in_as<span style="color:#006600; font-weight:bold;">&#40;</span>name<span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
...
&nbsp;
<span style="color:#9966CC; font-weight:bold;">Then</span> /the page header displays the caption <span style="color:#996600;">&quot;(.*)&quot;</span>/ <span style="color:#9966CC; font-weight:bold;">do</span> |caption|
    page_header.<span style="color:#9900CC;">should_contain</span><span style="color:#006600; font-weight:bold;">&#40;</span>caption<span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>The syntax is extremely flexible: Cucumber only cares about the Gherkin keywords “Given”, “When”, “Then”, “And” (plus a few others); everything else is simply matched against your regular expressions. Any tokens captured by capture groups in your regexes are passed to your step definition blocks as parameters. For web applications, it’s normal for your step definitions to work by using a browser automation library such as WatiN/WatiR or Selenium.</p>
<p>When you invoke Cucumber, it finds, parses and runs your .feature files, reporting the results (success in green, pending in yellow, failure in red):</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://blog.stevensanderson.com/wp-content/uploads/2010/03/image-thumb1.png" width="475" height="126" /></p>
<p>Because the GWT model inherently describes sequences of interactions, and because natural-language .feature files are inherently decoupled from the implementation code (they don’t mention the name of any classes or methods), this whole approach is a perfect fit for UI automation rather than unit-level testing.&#160; </p>
<p>Because you can describe scenarios in the language of your domain and user interface, your resulting feature files should make perfect sense to business experts. So, unlike traditional unit test driven development, this methodology can finally deliver on the promise of executable specifications that are actually useful as documentation.</p>
<h4>Doing it in .NET with SpecFlow</h4>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="image" border="0" alt="image" align="right" src="http://blog.stevensanderson.com/wp-content/uploads/2010/03/image-thumb2.png" width="240" height="101" /></p>
<p>As I mentioned, Cucumber itself is a Ruby tool. At the end of this blog post I’ll discuss some options for running the original Cucumber tool in a .NET environment, but for now let’s forget about that - you can sidestep all that complexity with SpecFlow.</p>
<p><a href="http://specflow.org/" target="_blank">SpecFlow</a> is an open-source .NET tool that lets you write specifications using 100%-Cucumber-compatible Gherkin syntax, and has a number of advantages over Cucumber itself:</p>
<ul>
<li><em>It integrates with Visual Studio</em>, which means you get File-&gt;New templates for creating new feature files </li>
<li>More crucially, <em>it gives complete VS debugger support</em>, so you can set breakpoints on Given/When/Then lines in your .feature files and step through their execution </li>
<li>You can implement your step definitions in <em>any .NET language </em></li>
<li>When you compile a project containing SpecFlow feature files, the output is an NUnit test assembly, so you can <em>use your favourite NUnit-compatible test runner or existing CI infrastructure</em> to run the specifications with no additional configuration. </li>
<li><em>It doesn’t have such a ridiculous name</em> <img src='http://blog.stevensanderson.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> It’s sad, but at one of my recent clients, several managers refused to take Cucumber seriously and wouldn’t pay attention to Cucumber specifications purely because of the name. That’s the real world for you! </li>
</ul>
<h4>Example: Combining ASP.NET MVC, SpecFlow, and WatiN</h4>
<p>To give you something concrete to get started with, I’ve made a <em>very</em> simple ASP.NET MVC 2 example application, built following the BDD workflow and with a full set of specs. To try it out,</p>
<ul>
<li>First <a href="http://specflow.org/" target="_blank">download and install SpecFlow</a> (choose either the VS2008 or VS2010 version) </li>
<li>Download and open the <a href="http://github.com/SteveSanderson/GuestbookDemo" target="_blank">Guestbook source code from Github</a> </li>
<li>Compile and open Guestbook.Spec.dll in <a href="http://www.nunit.org/" target="_blank">NUnit GUI</a> </li>
</ul>
<p>You should easily be able to understand in high-level terms what the application does by reading the Gherkin specifications. Just imagine these specifications are the written result of a design meeting where you’ve got your client or boss to tell you how the user interactions should work.</p>
<pre>
Feature: Browsing
   In order to see who's been on the site
   As a user
   I want to be able to view the list of posts

Scenario: Navigation to homepage
   When I navigate to /Guestbook
   Then I should be on the guestbook page

Scenario: Viewing existing entries
   Given I am on the guestbook page
   Then I should see a list of guestbook entries
    And guestbook entries have an author
    And guestbook entries have a posted date
    And guestbook entries have a comment
</pre>
<pre>
Feature: Posting
   In order to express my views
   As a user
   I want to be able to post entries into the guestbook

Scenario: Navigation to posting page
   Given I am on the guestbook page
   Then I should see a button labelled "Post a New Entry"
   When I click the button labelled "Post a New Entry"
   Then I am on the posting page

Scenario: Viewing the posting page
   Given I am on the posting page
   Then I should see a field labelled "Your name"
    And I should see a field labelled "Your comment"

Scenario: Posting a valid entry
   Given I am on the posting page
     And I have filled out the form as follows
       | Label          | Value             |
       | Your name      | Jakob             |
       | Your comment   | Das ist gut!      |
   When I click the button labelled "Post"
   Then I should be on the guestbook page
    And I see the flash message "Thanks for posting!"
    And the guestbook entries includes the following
       | Name      | Comment      | Posted date          |
       | Jakob     | Das ist gut! | (within last minute) |
</pre>
<p>Whenever you hit <em>save</em> while editing one of these files, SpecFlow generates a C# NUnit test fixture containing a [Test] method for each scenario. You don’t have to know or care about that, though. All you have to do is create step definitions in C# to match the lines in the Gherkin files. </p>
<p>At first, you won’t have any matching step definitions, so the NUnit test runner will show the tests as “inconclusive”:</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blog.stevensanderson.com/wp-content/uploads/2010/03/image-thumb3.png" width="640" height="328" /></p>
<p>Notice that in the “Text Output” tab it provides C# stub code to create a matching step definition. Here’s some examples of the finished step definitions, written using WatiN to automate a browser:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #000000;">&#91;</span>When<span style="color: #000000;">&#40;</span><span style="color: #A31515;">@"I navigate to (.*)&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #0000FF;">public</span> <span style="color: #0000FF;">void</span> WhenINavigateTo<span style="color: #000000;">&#40;</span><span style="color: #0000FF;">string</span> relativeUrl<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">var</span> rootUrl = <span style="color: #0000FF;">new</span> Uri<span style="color: #000000;">&#40;</span>ConfigurationManager.<span style="color: #0000FF;">AppSettings</span><span style="color: #000000;">&#91;</span><span style="color: #A31515;">&quot;RootUrl&quot;</span><span style="color: #000000;">&#93;</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #0000FF;">var</span> absoluteUrl = <span style="color: #0000FF;">new</span> Uri<span style="color: #000000;">&#40;</span>rootUrl, relativeUrl<span style="color: #000000;">&#41;</span>;
    WebBrowser.<span style="color: #0000FF;">Current</span>.<span style="color: #0000FF;">GoTo</span><span style="color: #000000;">&#40;</span>absoluteUrl<span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #000000;">&#91;</span>Then<span style="color: #000000;">&#40;</span><span style="color: #A31515;">@"I see the flash message &quot;</span><span style="color: #A31515;">&quot;(.*)&quot;</span><span style="color: #A31515;">&quot;&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #0000FF;">public</span> <span style="color: #0000FF;">void</span> ThenISeeTheFlashMessage<span style="color: #000000;">&#40;</span><span style="color: #0000FF;">string</span> message<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">var</span> flashElement = WebBrowser.<span style="color: #0000FF;">Current</span>.<span style="color: #0000FF;">Element</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;flashMessage&quot;</span><span style="color: #000000;">&#41;</span>;
    Assert.<span style="color: #0000FF;">That</span><span style="color: #000000;">&#40;</span>flashElement.<span style="color: #0000FF;">Text</span>, <span style="color: #0000FF;">Is</span>.<span style="color: #0000FF;">EqualTo</span><span style="color: #000000;">&#40;</span>message<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #000000;">&#91;</span>Given<span style="color: #000000;">&#40;</span><span style="color: #A31515;">@"I have filled out the form as follows&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #0000FF;">public</span> <span style="color: #0000FF;">void</span> GivenIHaveFilledOutTheFormAsFollows<span style="color: #000000;">&#40;</span>TechTalk.<span style="color: #0000FF;">SpecFlow</span>.<span style="color: #0000FF;">Table</span> table<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #0000FF;">var</span> row <span style="color: #0000FF;">in</span> table.<span style="color: #0000FF;">Rows</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
        <span style="color: #0000FF;">var</span> labelText = row<span style="color: #000000;">&#91;</span><span style="color: #A31515;">&quot;Label&quot;</span><span style="color: #000000;">&#93;</span> + <span style="color: #A31515;">&quot;:&quot;</span>;
        <span style="color: #0000FF;">var</span> value = row<span style="color: #000000;">&#91;</span><span style="color: #A31515;">&quot;Value&quot;</span><span style="color: #000000;">&#93;</span>;
        WebBrowser.<span style="color: #0000FF;">Current</span>.<span style="color: #0000FF;">TextFields</span>.<span style="color: #0000FF;">First</span><span style="color: #000000;">&#40;</span>Find.<span style="color: #0000FF;">ByLabelText</span><span style="color: #000000;">&#40;</span>labelText<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">TypeText</span><span style="color: #000000;">&#40;</span>value<span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>There’s lots more I could say about <a href="http://watin.sourceforge.net/" target="_blank">WatiN syntax</a> and <a href="http://www.engineyard.com/blog/2009/15-expert-tips-for-using-cucumber/" target="_blank">Gherkin best practices</a>, but this is a pretty long post already so I’ll leave that to others.</p>
<p>In case anyone’s wondering, I’m <strong>not</strong> trying to claim with this post that Cucumber-style UI automation tests are the one true way to do BDD, or that unit testing is dead. UI automation tends to be much more difficult to do than unit-level tests, because there are many more moving parts and you have to concern yourself with test data, setup and teardown, etc. <strong>Seriously, it is hard work,</strong> and requires a lot more persistence and dedication than mere unit testing, though it can also give many extra benefits especially with regard to detecting regressions.</p>
<h4>What about Running Cucumber Itself on .NET?</h4>
<p>If, for some reason, you don’t want to use SpecFlow and would rather run the original Ruby-based Cucumber tool, there are two main options for .NET programmers:</p>
<ul>
<li><strong>Use <a href="http://ironruby.net/" target="_blank">IronRuby</a></strong>. The current version of IronRuby is entirely capable of running Cucumber. It isn’t as easy to set up as SpecFlow, but only took me 30 minutes or so. The drawbacks are that (1) you have to write step definitions in Ruby, unless someone can come up with a clever way to call arbitrary .NET methods directly, (2) it runs Cucumber pretty slowly, at least in my testing, and (3) it doesn’t trivially integrate with existing CI infrastructure like an NUnit-based solution does. </li>
<li><strong>Use <a href="http://github.com/richardlawrence/Cuke4Nuke" target="_blank">Cuke4Nuke</a></strong>. This is an open-source project that aims to bridge the gap between the original Cucumber tool running on any Ruby interpreter (not necessarily IronRuby) and step definitions written in .NET. It works by hosting your .NET step definitions in a small .NET-based “server” application, which Cucumber communicates with over a TCP/IP connection. I must admit I had a bad experience trying to make this work – it took hours. The latest Ruby interpreter didn’t include all the necessary libraries for Cuke4Nuke, and then when I’d hacked all the dependencies together, it wasn’t clear to me where to put the magic “cucumber.wire” file or what parameters you can use with the .NET server app. And then it was also pretty slow compared to keeping everything in .NET with SpecFlow. And it had a very limited API for running setup/teardown code around scenarios. </li>
</ul>
<p>If you want to write step definitions in a .NET language, I don&#8217;t know why you wouldn&#8217;t just use SpecFlow. Since it&#8217;s 100% Gherkin-compatible, your feature files could in future be moved to a different implementation if desired. If you’ve tried others, I’d be interested to hear about your experiences. And no, I haven&#8217;t tried <a href="http://specter.sourceforge.net/" target="_blank">Spectre</a> yet.</p>
<h4>Injecting Mocks into a Running ASP.NET Application</h4>
<p>In <a href='/2010/03/09/deleporter-cross-process-code-injection-for-aspnet/'>the next post</a>, I’ll show you one possible way to simplify or speed up UI-level specifications a little. It’s a cross-process code injection library that, among other things, you can use to inject a mock database into a running ASP.NET application without it knowing about it. Or, you can override configuration, or maybe simulate the passing of time.</p>
<p>Sometimes, it isn&#8217;t desirable to meddle with your app&#8217;s internals, but sometimes it is. Ruby coders can already do it using <a href="http://wiki.github.com/brynary/webrat/" target="_blank">Webrat</a> or <a href="http://github.com/ngty/cross-stub" target="_blank">cross-stub</a>, and I&#8217;ve found reasons to want that power over .NET apps too.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fblog.stevensanderson.com%2f2010%2f03%2f03%2fbehavior-driven-development-bdd-with-specflow-and-aspnet-mvc%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fblog.stevensanderson.com%2f2010%2f03%2f03%2fbehavior-driven-development-bdd-with-specflow-and-aspnet-mvc%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<div class="feedflare">
<a href="http://feeds.codeville.net/~ff/SteveCodeville?a=RBNm3XN1ERw:1vuG99oA8go:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?i=RBNm3XN1ERw:1vuG99oA8go:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=RBNm3XN1ERw:1vuG99oA8go:G79ilh31hkQ"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?d=G79ilh31hkQ" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=RBNm3XN1ERw:1vuG99oA8go:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?i=RBNm3XN1ERw:1vuG99oA8go:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=RBNm3XN1ERw:1vuG99oA8go:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/SteveCodeville/~4/RBNm3XN1ERw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.stevensanderson.com/2010/03/03/behavior-driven-development-bdd-with-specflow-and-aspnet-mvc/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.stevensanderson.com/2010/03/03/behavior-driven-development-bdd-with-specflow-and-aspnet-mvc/</feedburner:origLink></item>
		<item>
		<title>Partial Validation in ASP.NET MVC 2</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/9F_3AhkfYmQ/</link>
		<comments>http://blog.stevensanderson.com/2010/02/19/partial-validation-in-aspnet-mvc-2/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 18:23:42 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[ASP.NET]]></category>

		<category><![CDATA[MVC]]></category>

		<category><![CDATA[Validation]]></category>

		<guid isPermaLink="false">http://blog.stevensanderson.com/2010/02/19/partial-validation-in-aspnet-mvc-2/</guid>
		<description><![CDATA[It’s tiny tip time…
Since all the fuss about [Required] validators in ASP.NET MVC 2, the validation behaviour was changed in Release Candidate 2. Previously, the framework only validated fields that were actually posted in the form, whereas now it validates all the fields on any model object that the model binder gives you. Most people [...]]]></description>
			<content:encoded><![CDATA[<p>It’s tiny tip time…</p>
<p>Since <a href="http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html">all the fuss about [Required] validators</a> in ASP.NET MVC 2, the validation behaviour was changed in Release Candidate 2. Previously, the framework only validated fields that were actually posted in the form, whereas now it validates <em>all</em> the fields on any model object that the model binder gives you. Most people prefer this new behaviour, because they don’t like the idea that someone can avoid a [Required] rule just by using FireBug or similar to delete the HTML form field. That’s pretty understandable, and well done to the MVC team for agreeing to this change so late in the production cycle.</p>
<p>However, there’s a drawback to this change of behaviour. What about when you want <em>partial validation</em> (i.e., validating only a subset of your model’s fields)? Maybe your screen only provides input controls for a subset of fields. In fact, right now, I’m making a multi-step wizard, sharing a single model class across all steps (because it’s convenient). Obviously I don’t want to show errors on step 1 about fields that appear on step 2, especially not “<strong>A value for <em>(some field you can’t see)</em> is required.</strong>”</p>
<h4>Doing Partial Validation</h4>
<p>In this specific case, the pre-RC2 behaviour would have been more convenient. I only want to validate the values that were actually posted on each step. A very simple way of achieving that is to use this action filter:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> <span style="color: #0000FF;">class</span> ValidateOnlyIncomingValuesAttribute : ActionFilterAttribute
<span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">override</span> <span style="color: #0000FF;">void</span> OnActionExecuting<span style="color: #000000;">&#40;</span>ActionExecutingContext filterContext<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0000FF;">var</span> modelState = filterContext.<span style="color: #0000FF;">Controller</span>.<span style="color: #0000FF;">ViewData</span>.<span style="color: #0000FF;">ModelState</span>;
        <span style="color: #0000FF;">var</span> valueProvider = filterContext.<span style="color: #0000FF;">Controller</span>.<span style="color: #0000FF;">ValueProvider</span>;
&nbsp;
        <span style="color: #0000FF;">var</span> keysWithNoIncomingValue = modelState.<span style="color: #0000FF;">Keys</span>.<span style="color: #0000FF;">Where</span><span style="color: #000000;">&#40;</span>x =&gt; !valueProvider.<span style="color: #0000FF;">ContainsPrefix</span><span style="color: #000000;">&#40;</span>x<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
        <span style="color: #0000FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #0000FF;">var</span> key <span style="color: #0000FF;">in</span> keysWithNoIncomingValue<span style="color: #000000;">&#41;</span>
            modelState<span style="color: #000000;">&#91;</span>key<span style="color: #000000;">&#93;</span>.<span style="color: #0000FF;">Errors</span>.<span style="color: #0000FF;">Clear</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Now, if you use this filter on a controller or action method&#8230;</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #000000;">&#91;</span>ValidateOnlyIncomingValues<span style="color: #000000;">&#93;</span>
<span style="color: #0000FF;">public</span> <span style="color: #0000FF;">class</span> SomeController : Controller
<span style="color: #000000;">&#123;</span>
   <span style="color: #008000;">// ...</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>then the filter will discard any validation errors that correspond to fields that were not even posted during this request.</p>
<h4>But what about security?</h4>
<p>Obviously this means that someone can bypass my [Required] rules by modifying their HTTP posts so they don’t include any key-value pair for any given field. </p>
<p>This is no problem at all. My real validation logic is all in the domain layer, so it doesn’t really matter what happens in the UI layer. The validation feedback from the UI layer is only for the end user’s convenience – if they choose to bypass it, they’ll just get an error message later.</p>
<div class="feedflare">
<a href="http://feeds.codeville.net/~ff/SteveCodeville?a=9F_3AhkfYmQ:HRPhsTCILtI:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?i=9F_3AhkfYmQ:HRPhsTCILtI:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=9F_3AhkfYmQ:HRPhsTCILtI:G79ilh31hkQ"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?d=G79ilh31hkQ" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=9F_3AhkfYmQ:HRPhsTCILtI:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?i=9F_3AhkfYmQ:HRPhsTCILtI:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=9F_3AhkfYmQ:HRPhsTCILtI:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/SteveCodeville/~4/9F_3AhkfYmQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.stevensanderson.com/2010/02/19/partial-validation-in-aspnet-mvc-2/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.stevensanderson.com/2010/02/19/partial-validation-in-aspnet-mvc-2/</feedburner:origLink></item>
		<item>
		<title>Validating a variable length list, ASP.NET MVC 2-style</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/hrHNa5-tdNI/</link>
		<comments>http://blog.stevensanderson.com/2010/01/28/validating-a-variable-length-list-aspnet-mvc-2-style/#comments</comments>
		<pubDate>Thu, 28 Jan 2010 16:36:40 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[MVC]]></category>

		<category><![CDATA[UI]]></category>

		<category><![CDATA[Validation]]></category>

		<guid isPermaLink="false">http://blog.stevensanderson.com/2010/01/28/validating-a-variable-length-list-aspnet-mvc-2-style/</guid>
		<description><![CDATA[In the previous post I showed a fairly straightforward way to create an editor where the user can add and delete the items in a set. Please read that previous post before continuing to read this one.

But what about validation? We don’t like your blank item names or your negative prices, sonny! 
As you probably [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://blog.codeville.net/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/">the previous post</a> I showed a fairly straightforward way to create an editor where the user can add and delete the items in a set. <i>Please read that previous post before continuing to read this one.</i></p>
<p><img alt="image" src="http://blog.codeville.net/wp-content/uploads/2010/01/image-thumb3.png" /></p>
<p>But what about validation? We don’t like your blank item names or your negative prices, sonny! </p>
<p>As you probably know, ASP.NET MVC 2 supports DataAnnotations attributes out of the box, so you can mark up your model as follows.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> <span style="color: #0000FF;">class</span> Gift
<span style="color: #000000;">&#123;</span>
    <span style="color: #000000;">&#91;</span>Required<span style="color: #000000;">&#93;</span>
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">string</span> Name <span style="color: #000000;">&#123;</span> get; set; <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #000000;">&#91;</span>Range<span style="color: #000000;">&#40;</span><span style="color: #000000;">0.01</span>, <span style="color: #0000FF;">double</span>.<span style="color: #0000FF;">MaxValue</span>, ErrorMessage = <span style="color: #A31515;">&quot;Please enter a price above zero.&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">double</span> Price <span style="color: #000000;">&#123;</span> get; set; <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<h4>Server-side validation</h4>
<p>Server-side validation is trivial, assuming you want to use the default model binder convention of validating each model object when it’s bound. In the action that receives the form post, just check ModelState.IsValid, and refuse to accept the data if it isn’t.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #000000;">&#91;</span>HttpPost<span style="color: #000000;">&#93;</span>
<span style="color: #0000FF;">public</span> ActionResult Index<span style="color: #000000;">&#40;</span>IEnumerable&lt;Gift&gt; gifts<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">if</span> <span style="color: #000000;">&#40;</span>ModelState.<span style="color: #0000FF;">IsValid</span><span style="color: #000000;">&#41;</span>
        <span style="color: #0000FF;">return</span> View<span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;Completed&quot;</span>, gifts<span style="color: #000000;">&#41;</span>;
    <span style="color: #0000FF;">else</span>
        <span style="color: #0000FF;">return</span> View<span style="color: #000000;">&#40;</span>gifts<span style="color: #000000;">&#41;</span>; <span style="color: #008000;">// Redisplay the form with errors</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>You’ll also need to specify where the validation error messages should appear. Update the <strong>GiftEditorRow.ascx</strong> partial by placing a couple of <strong>Html.ValidationMessageFor()</strong> helpers somewhere inside the row.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp">&lt;%= Html.<span style="color: #0000FF;">ValidationMessageFor</span><span style="color: #000000;">&#40;</span>x =&gt; x.<span style="color: #0000FF;">Name</span><span style="color: #000000;">&#41;</span> %&gt;
&lt;%= Html.<span style="color: #0000FF;">ValidationMessageFor</span><span style="color: #000000;">&#40;</span>x =&gt; x.<span style="color: #0000FF;">Price</span><span style="color: #000000;">&#41;</span> %&gt;</pre></div></div>

<p>Now, if the incoming data doesn’t satisfy your rules, the form will be re-rendered, displaying appropriate messages.</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://blog.codeville.net/wp-content/uploads/2010/01/image-thumb4.png" width="620" height="334" /></p>
<h4>Client-side validation</h4>
<p>It gets a bit more complicated if you also want client-side validation. You could use <a href="http://codeplex.com/xval">xVal</a> (I&#8217;m not sure whether it would be easier or harder), but I want to get better acquainted with ASP.NET MVC 2’s built-in client-side validation feature, so I’m going to use that.</p>
<p>I don’t even know if there’s an officially recommended way of doing ASP.NET MVC 2 client-side validation when you’re dynamically adding and removing form elements, but I’ll show you a technique I found that will do it. <strong>Be warned: this is rather hacky</strong>. I’d be interested to hear if anyone can suggest a better way.</p>
<p>First, let’s set up client-side validation in the normal way. Enable client-side validation on your form by calling <b>Html.EnableClientValidation()</b>:</p>

<div class="wp_syntax"><div class="code"><pre>&lt;h2&gt;Gift List&lt;/h2&gt;
What do you want for your birthday?
&nbsp;
&lt;% Html.EnableClientValidation(); %&gt;
&lt;% using(Html.BeginForm()) { %&gt;
    (rest as before)
&lt;% } %&gt;</pre></div></div>

<p>Now, as long as you’ve already referenced MicrosoftAjax.js and MicrosoftMvcValidation.js, you can run the app and you’ll immediately get working client-side validation! But hang on a minute… it only works for the elements that are present when the form is first rendered, *not* the elements added when the user clicks “Add another…”.</p>
<p>We need a way to capture the extra validation rules added each time the user adds a new row and somehow attach them to the form. One possible approach is to create a new type of custom view result that registers the validators associated with any partial that is renders, and have it emit some JavaScript to attach those validators to the form.</p>
<p>Here’s a possible implementation. Don’t worry if you don’t understand it.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> <span style="color: #0000FF;">class</span> AjaxViewResult : ViewResult
<span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">string</span> UpdateValidationForFormId <span style="color: #000000;">&#123;</span> get; set; <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0000FF;">public</span> AjaxViewResult<span style="color: #000000;">&#40;</span><span style="color: #0000FF;">string</span> viewName, <span style="color: #0000FF;">object</span> model<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        ViewName = viewName;
        ViewData = <span style="color: #0000FF;">new</span> ViewDataDictionary <span style="color: #000000;">&#123;</span> Model = model <span style="color: #000000;">&#125;</span>;
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">override</span> <span style="color: #0000FF;">void</span> ExecuteResult<span style="color: #000000;">&#40;</span>ControllerContext context<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0000FF;">var</span> result = <span style="color: #0000FF;">base</span>.<span style="color: #0000FF;">FindView</span><span style="color: #000000;">&#40;</span>context<span style="color: #000000;">&#41;</span>;
        <span style="color: #0000FF;">var</span> viewContext = <span style="color: #0000FF;">new</span> ViewContext<span style="color: #000000;">&#40;</span>context, result.<span style="color: #0000FF;">View</span>, ViewData, TempData, context.<span style="color: #0000FF;">HttpContext</span>.<span style="color: #0000FF;">Response</span>.<span style="color: #0000FF;">Output</span><span style="color: #000000;">&#41;</span>;
&nbsp;
        BeginCapturingValidation<span style="color: #000000;">&#40;</span>viewContext<span style="color: #000000;">&#41;</span>;
        <span style="color: #0000FF;">base</span>.<span style="color: #0000FF;">ExecuteResult</span><span style="color: #000000;">&#40;</span>context<span style="color: #000000;">&#41;</span>;
        EndCapturingValidation<span style="color: #000000;">&#40;</span>viewContext<span style="color: #000000;">&#41;</span>;
&nbsp;
        result.<span style="color: #0000FF;">ViewEngine</span>.<span style="color: #0000FF;">ReleaseView</span><span style="color: #000000;">&#40;</span>context, result.<span style="color: #0000FF;">View</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0000FF;">private</span> <span style="color: #0000FF;">void</span> BeginCapturingValidation<span style="color: #000000;">&#40;</span>ViewContext viewContext<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0000FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #0000FF;">string</span>.<span style="color: #0000FF;">IsNullOrEmpty</span><span style="color: #000000;">&#40;</span>UpdateValidationForFormId<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
            <span style="color: #0000FF;">return</span>;
        viewContext.<span style="color: #0000FF;">ClientValidationEnabled</span> = <span style="color: #0000FF;">true</span>;
        viewContext.<span style="color: #0000FF;">FormContext</span> = <span style="color: #0000FF;">new</span> FormContext <span style="color: #000000;">&#123;</span> FormId = UpdateValidationForFormId <span style="color: #000000;">&#125;</span>;
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0000FF;">private</span> <span style="color: #0000FF;">void</span> EndCapturingValidation<span style="color: #000000;">&#40;</span>ViewContext viewContext<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0000FF;">if</span> <span style="color: #000000;">&#40;</span>!viewContext.<span style="color: #0000FF;">ClientValidationEnabled</span><span style="color: #000000;">&#41;</span>
            <span style="color: #0000FF;">return</span>;
        viewContext.<span style="color: #0000FF;">OutputClientValidation</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
        viewContext.<span style="color: #0000FF;">Writer</span>.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;&lt;script type=<span style="color: #008080; font-weight: bold;">\&quot;</span>text/javascript<span style="color: #008080; font-weight: bold;">\&quot;</span>&gt;Sys.Mvc.FormContext._Application_Load()&lt;/script&gt;&quot;</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Now, we can change the BlankEditorRow() action method to render its partial using this custom view result.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> ViewResult BlankEditorRow<span style="color: #000000;">&#40;</span><span style="color: #0000FF;">string</span> formId<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">return</span> <span style="color: #0000FF;">new</span> AjaxViewResult<span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;GiftEditorRow&quot;</span>, <span style="color: #0000FF;">new</span> Gift<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span> UpdateValidationForFormId = formId <span style="color: #000000;">&#125;</span>;
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>You’ll notice that BlankEditorRow() now needs to be told which form it should attach the new validators to. You’ll have to update the link to BlankEditorRow to add this information to the query string.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp">&lt;%= Html.<span style="color: #0000FF;">ActionLink</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;Add another...&quot;</span>, <span style="color: #A31515;">&quot;BlankEditorRow&quot;</span>, <span style="color: #0000FF;">new</span> <span style="color: #000000;">&#123;</span> ViewContext.<span style="color: #0000FF;">FormContext</span>.<span style="color: #0000FF;">FormId</span> <span style="color: #000000;">&#125;</span>, <span style="color: #0000FF;">new</span> <span style="color: #000000;">&#123;</span> id = <span style="color: #A31515;">&quot;addItem&quot;</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span> %&gt;</pre></div></div>

<p>Et voila! Each time the user appends a new row, its validators will magically be associated with the form.</p>
<h5>The problem with removing fields</h5>
<p>If you proceed with this approach, you’ll soon discover a further flaw. Even if the user removes fields from the form, any validators associated with those fields will still be lurking.&#160; If a field is displaying a “required” error message, and then the user deletes the containing row, it will become impossible to submit the form because the field is still required, except now there is nowhere to enter any data for it. Whoops!</p>
<p>Again, I don’t know if there’s a recommended way to deal with this, but one possibility is to edit the MicrosoftMvcValidation.debug.js script a little. Let’s update the logic slightly so that, if a validator is associated with fields that no longer exist, the validator should no longer apply.</p>
<p>Find the function called “Sys_Mvc_FieldContext$validate”, and right at the top, add the following:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #009900; font-style: italic;">// [Added] Permanently disable this validator if its associated elements are no longer in the document</span>
<span style="color: #000066; font-weight: bold;">for</span> <span style="color: #66cc66;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> j = <span style="color: #CC0000;">0</span>; j &lt; <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">elements</span>.<span style="color: #006600;">length</span>; j++<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #66cc66;">&#40;</span>!Sys.<span style="color: #006600;">Mvc</span>.<span style="color: #006600;">FormContext</span>._isElementInHierarchy<span style="color: #66cc66;">&#40;</span>document.<span style="color: #006600;">body</span>, <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">elements</span><span style="color: #66cc66;">&#91;</span>j<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">validations</span> = <span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span>;
        <span style="color: #000066; font-weight: bold;">break</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Now, assuming you’re referencing the file you just edited (MicrosoftMvcValidation.debug.js, rather than MicrosoftMvcValidation.js), you should get the desired change in behaviour. Deleting a row in the editor now kills its associated validation rules properly, so they don’t rise from the grave and block form submissions like invisible validation zombies.</p>
<h4>Summary</h4>
<p>Once you’ve got the AjaxViewResult class, it doesn’t take <em>that</em> much work to enable client-side validation on dynamically changing forms. Maybe there’s a better and less hacky way though… Anybody got any suggestions?</p>
<p>
<ul>
<li><a href="http://blog.codeville.net/blogfiles/2010/January/ListEditorDemo-WithValidation.zip">Download the completed demo project (78kb)</a></li>
</ul>
<div class="feedflare">
<a href="http://feeds.codeville.net/~ff/SteveCodeville?a=hrHNa5-tdNI:Usp7PyUx0X8:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?i=hrHNa5-tdNI:Usp7PyUx0X8:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=hrHNa5-tdNI:Usp7PyUx0X8:G79ilh31hkQ"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?d=G79ilh31hkQ" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=hrHNa5-tdNI:Usp7PyUx0X8:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?i=hrHNa5-tdNI:Usp7PyUx0X8:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=hrHNa5-tdNI:Usp7PyUx0X8:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/SteveCodeville/~4/hrHNa5-tdNI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.stevensanderson.com/2010/01/28/validating-a-variable-length-list-aspnet-mvc-2-style/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.stevensanderson.com/2010/01/28/validating-a-variable-length-list-aspnet-mvc-2-style/</feedburner:origLink></item>
		<item>
		<title>Editing a variable length list, ASP.NET MVC 2-style</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/WuqlFqGTJrQ/</link>
		<comments>http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/#comments</comments>
		<pubDate>Thu, 28 Jan 2010 15:02:46 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[MVC]]></category>

		<category><![CDATA[UI]]></category>

		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://blog.codeville.net/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/</guid>
		<description><![CDATA[A while back I posted about a way of editing a list of items where the user can add or remove as many items as they want. Tim Scott later provided some helpers to make the code neater. Now, I find myself making use of this technique so often that I thought it would be [...]]]></description>
			<content:encoded><![CDATA[<p>A while back I posted about <a href="http://blog.codeville.net/2008/12/22/editing-a-variable-length-list-of-items-in-aspnet-mvc/" target="_blank">a way of editing a list of items</a> where the user can add or remove as many items as they want. <a href="http://lunaverse.wordpress.com/2009/01/13/editing-a-variable-length-list-of-items-with-mvccontribfluenthtml-take-2/" target="_blank">Tim Scott later provided</a> some helpers to make the code neater. Now, I find myself making use of this technique so often that I thought it would be worthwhile providing an update to show how you can do it even more easily with ASP.NET MVC 2 because of its strongly-typed and templated input helpers.</p>
<p><a href="http://blog.codeville.net/blogfiles/2010/January/ListEditorDemo.zip">Download the demo project</a> or read on for details.</p>
<p><i><b>Update (Feb 11, 2010):</b>Thanks to <a href="http://ryanrivest.com/blog/">Ryan Rivest</a> for pointing out a bug in the original code and providing a neat fix. Code updated.</i></p>
<h4>Getting Started</h4>
<p>For this example I’m going to go with the same theme as last time and build a gift list editor. Our model object can simply be the following:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> <span style="color: #0000FF;">class</span> Gift
<span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">string</span> Name <span style="color: #000000;">&#123;</span> get; set; <span style="color: #000000;">&#125;</span>
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">double</span> Price <span style="color: #000000;">&#123;</span> get; set; <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<h4>Displaying the Initial UI</h4>
<p>To display the initial data entry screen, add an action method that renders a view and passes some initial collection of Gift instances.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> ActionResult Index<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">var</span> initialData = <span style="color: #0000FF;">new</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#123;</span>
        <span style="color: #0000FF;">new</span> Gift <span style="color: #000000;">&#123;</span> Name = <span style="color: #A31515;">&quot;Tall Hat&quot;</span>, Price = <span style="color: #000000;">39.95</span> <span style="color: #000000;">&#125;</span>,
        <span style="color: #0000FF;">new</span> Gift <span style="color: #000000;">&#123;</span> Name = <span style="color: #A31515;">&quot;Long Cloak&quot;</span>, Price = <span style="color: #000000;">120.00</span> <span style="color: #000000;">&#125;</span>,
    <span style="color: #000000;">&#125;</span>;
    <span style="color: #0000FF;">return</span> View<span style="color: #000000;">&#40;</span>initialData<span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Next, add a view for this action, and make it strongly-typed with a model class of <strong>IEnumerable&lt;Gift&gt;</strong>. We’ll create an HTML form, and for each gift in the collection, we’ll render a partial to display an editor for that gift. </p>

<div class="wp_syntax"><div class="code"><pre class="csharp">&lt;h2&gt;Gift List&lt;/h2&gt;
What <span style="color: #0000FF;">do</span> you want <span style="color: #0000FF;">for</span> your birthday?
&nbsp;
&lt;% <span style="color: #0000FF;">using</span><span style="color: #000000;">&#40;</span>Html.<span style="color: #0000FF;">BeginForm</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span> %&gt;
    &lt;div id=<span style="color: #A31515;">&quot;editorRows&quot;</span>&gt;
        &lt;% <span style="color: #0000FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #0000FF;">var</span> item <span style="color: #0000FF;">in</span> Model<span style="color: #000000;">&#41;</span>
            Html.<span style="color: #0000FF;">RenderPartial</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;GiftEditorRow&quot;</span>, item<span style="color: #000000;">&#41;</span>;
        %&gt;
    &lt;/div&gt;
&nbsp;
    &lt;input type=<span style="color: #A31515;">&quot;submit&quot;</span> value=<span style="color: #A31515;">&quot;Finished&quot;</span> /&gt;
&lt;% <span style="color: #000000;">&#125;</span> %&gt;</pre></div></div>

<p>I know it would be possible to use ASP.NET MVC 2’s Html.EditorFor() or Html.EditorForModel() helpers, but later on we’re going to need more control over the HTML field ID prefixes so in this example it turns out to be easier just to use Html.RenderPartial().</p>
<p>Next, to display the editor for each gift in the sequence, add a new partial view at <strong>/Views/<em>controllerName</em>/GiftEditorRow.ascx</strong>, strongly-typed with a model class of Gift, containing:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp">&lt;div <span style="color: #0000FF;">class</span>=<span style="color: #A31515;">&quot;editorRow&quot;</span>&gt;
    &lt;% <span style="color: #0000FF;">using</span><span style="color: #000000;">&#40;</span>Html.<span style="color: #0000FF;">BeginCollectionItem</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;gifts&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span> %&gt;
        Item: &lt;%= Html.<span style="color: #0000FF;">TextBoxFor</span><span style="color: #000000;">&#40;</span>x =&gt; x.<span style="color: #0000FF;">Name</span><span style="color: #000000;">&#41;</span> %&gt; 
        Value: $&lt;%= Html.<span style="color: #0000FF;">TextBoxFor</span><span style="color: #000000;">&#40;</span>x =&gt; x.<span style="color: #0000FF;">Price</span>, <span style="color: #0000FF;">new</span> <span style="color: #000000;">&#123;</span> size = <span style="color: #000000;">4</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span> %&gt; 
    &lt;% <span style="color: #000000;">&#125;</span> %&gt;
&lt;/div&gt;</pre></div></div>

<p>Here’s where we get to start using ASP.NET MVC 2 features and make things slightly easier than before. Notice that I’m using strongly-typed input helpers (<strong>Html.TextBoxFor()</strong>) to avoid the need to build element IDs manually. These helpers are smart enough to detect the “template context” in which they are being rendered, and use any field ID prefix associated with that template context.</p>
<p>You might also be wondering what <strong>Html.BeginCollectionItem()</strong> is. It’s a HTML helper I made that you can use when rendering a sequence of items that should later be model bound to a single collection. You give it some name for your collection, and it opens a new template context for that collection name, plus a random unique field ID prefix. It also automatically renders a hidden field, which in this case is called <strong>gifts.index</strong>, populating it with that unique ID, so when you later model bind to a list, ASP.NET MVC 2 will know that all the fields in this context should be associated with a single .NET object.</p>
<p>And now, if you visit the Index() action, you should see the editor&#160; as shown below. (I’ve added some CSS styles, obviously.)</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blog.codeville.net/wp-content/uploads/2010/01/image-thumb2.png" width="517" height="379" /></p>
<h4>Receiving the Form Post</h4>
<p>To receive the data posted by the user, add a new action method as follows. </p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #000000;">&#91;</span>HttpPost<span style="color: #000000;">&#93;</span>
<span style="color: #0000FF;">public</span> ActionResult Index<span style="color: #000000;">&#40;</span>IEnumerable&lt;Gift&gt; gifts<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #008000;">// To do: do whatever you want with the data</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>How easy is that? Because <strong>Html.BeginCollectionItem()</strong> observes ASP.NET MVC 2 model binding conventions, you can receive all the items in the list without having to do anything funky.</p>
<p>You could also achieve the same with less code by using the built-in <strong>Html.EditorFor()</strong> or <strong>Html.EditorForModel()</strong> helpers, but because these use a different indexing convention (an ascending sequence, not a set of random unique keys), things would get more difficult when you try to add or remove items dynamically.</p>
<h4>Dynamically Adding Items</h4>
<p>If the user wants to add another item, they’ll need something to click to say so. Let’s add an “Add another…” link. Add the following to the main view, just before the “Finished” button.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp">&lt;%= Html.<span style="color: #0000FF;">ActionLink</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;Add another...&quot;</span>, <span style="color: #A31515;">&quot;BlankEditorRow&quot;</span>, <span style="color: #0000FF;">null</span>, <span style="color: #0000FF;">new</span> <span style="color: #000000;">&#123;</span> id = <span style="color: #A31515;">&quot;addItem&quot;</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span> %&gt;</pre></div></div>

<p>This is a link to an action called <strong>BlankEditorRow</strong> which doesn’t exist yet. The idea is that the <strong>BlankEditorRow</strong> action will return the HTML markup for a new blank row. We can fetch this markup via Ajax and dynamically append it into the page.</p>
<p>To make this Ajax call and append the result into the page, make sure you’ve got jQuery referenced, and create a click handler similar to this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript">$<span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;#addItem&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">click</span><span style="color: #66cc66;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    $.<span style="color: #006600;">ajax</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#123;</span>
        url: <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">href</span>,
        cache: <span style="color: #003366; font-weight: bold;">false</span>,
        success: <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>html<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> $<span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;#editorRows&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">append</span><span style="color: #66cc66;">&#40;</span>html<span style="color: #66cc66;">&#41;</span>; <span style="color: #66cc66;">&#125;</span>
    <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">false</span>;
<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>Note that it’s very important to tell jQuery to tell the browser not to re-use cached responses, otherwise those unique IDs won’t always be so unique&#8230; And before we forget, we’ll need to put the BlankEditorRow action in place:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> ViewResult BlankEditorRow<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">return</span> View<span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;GiftEditorRow&quot;</span>, <span style="color: #0000FF;">new</span> Gift<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>As you can see, it simply renders the same editor partial, passing a blank Gift object to represent the initial state. I’m very pleased that you can re-use the same editor partial in this way – it means there’s no duplication of view markup and we can stay totally <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY</a>.</p>
<p>And that, in fact, is all you have to do – each time the user clicks “Add another…”, the client-side code will inject a new blank row into the editor. Because each row has its own unique ID, when the user later posts the form, all the data will be model bound into a single IEnumerable&lt;Gift&gt;.</p>
<h4>Dynamically Removing Items</h4>
<p>Removing items is easier, because all you have to do is remove the corresponding DOM elements from the HTML document. If the elements are gone, their contents won’t be posted to the server, so they won’t be present in the IEnumerable&lt;Gift&gt; that your action receives.</p>
<p>Add a “delete” link to the GiftEditorRow.ascx partial:</p>

<div class="wp_syntax"><div class="code"><pre>&lt;a href=&quot;#&quot; class=&quot;deleteRow&quot;&gt;delete&lt;/a&gt;</pre></div></div>

<p>This needs to go inside the DIV with class “editorRow”, so you can handle clicks on it as follows:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript">$<span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;a.deleteRow&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">live</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;click&quot;</span>, <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    $<span style="color: #66cc66;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">parents</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;div.editorRow:first&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">remove</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">false</span>;
<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>Notice that this code uses jQuery’s “live” function, which tells it to apply the click handler not only to the elements that exist when the page is first loaded, but also to any matching elements that are dynamically added later.</p>
<p>You’ve now got a working editor with “add” and “delete” functionality.</p>
<p>
<img src='http://blog.codeville.net/wp-content/uploads/2010/01/editor-screenshot.png' alt='editor-screenshot.png' />
</p>
<h4>Summary</h4>
<p>I hope you can see that editing variable-length lists can be very easy. Other than the reusable Html.BeginCollectionItem() helper, I’ve just shown you every line of code needed for this particular strategy, and in total it’s just 36 lines (including the model, action methods, views, and JavaScript, but excluding lines that are purely whitespace or braces).</p>
<p><a href="http://blog.codeville.net/blogfiles/2010/January/ListEditorDemo.zip">Download the full demo project</a></p>
<h4>But what about validation?</h4>
<p>Yes, I haven’t forgotten about that! You can already do your server-side validation any way you want – by default the model binder will respect any rules associated with your model.</p>
<p>In the <a href="/2010/01/28/validating-a-variable-length-list-aspnet-mvc-2-style/">next post</a>, I’ll show how you can integrate this list editing strategy with ASP.NET MVC 2’s client-side validation feature.</p>
<div class="feedflare">
<a href="http://feeds.codeville.net/~ff/SteveCodeville?a=WuqlFqGTJrQ:6I0Rv4zZJcU:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?i=WuqlFqGTJrQ:6I0Rv4zZJcU:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=WuqlFqGTJrQ:6I0Rv4zZJcU:G79ilh31hkQ"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?d=G79ilh31hkQ" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=WuqlFqGTJrQ:6I0Rv4zZJcU:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?i=WuqlFqGTJrQ:6I0Rv4zZJcU:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=WuqlFqGTJrQ:6I0Rv4zZJcU:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/SteveCodeville/~4/WuqlFqGTJrQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/</feedburner:origLink></item>
		<item>
		<title>Measuring the Performance of Asynchronous Controllers</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/ex_U-97lKTo/</link>
		<comments>http://blog.stevensanderson.com/2010/01/25/measuring-the-performance-of-asynchronous-controllers/#comments</comments>
		<pubDate>Mon, 25 Jan 2010 08:07:43 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[ASP.NET]]></category>

		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://blog.codeville.net/2010/01/25/measuring-the-performance-of-asynchronous-controllers/</guid>
		<description><![CDATA[Recently I’ve been working with ASP.NET MVC 2.0’s new asynchronous controllers. The idea with these is that you can split the request handling pipeline into two phases:

First, your controller begins one or more external I/O calls (e.g., SQL database calls or web service calls). Without waiting for them to complete, it releases the thread back [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I’ve been working with ASP.NET MVC 2.0’s new <em>asynchronous controllers</em>. The idea with these is that you can split the request handling pipeline into two phases:</p>
<ul>
<li>First, your controller begins one or more external I/O calls (e.g., SQL database calls or web service calls). Without waiting for them to complete, it releases the thread back into the ASP.NET worker thread pool so that it can deal with other requests. </li>
<li>Later, when all of the external I/O calls have completed, the underlying ASP.NET platform grabs another free worker thread from the pool, reattaches it to your original HTTP context, and lets it complete handling the original request. </li>
</ul>
<p>This is intended to boost your server’s capacity. Because you don’t have so many worker threads blocked while waiting for I/O, you can handle many more concurrent requests. A while back I blogged about <a href="http://blog.codeville.net/2008/04/05/improve-scalability-in-aspnet-mvc-using-asynchronous-requests/">a way of doing this with an early preview release</a> of ASP.NET MVC 1.0, but now in ASP.NET MVC 2.0 it’s a natively supported feature.</p>
<p>In this blog post I’m not going to explain how to create or work with asynchronous controllers. That’s already described <a href="http://msdn.microsoft.com/en-us/library/ee728598(VS.100).aspx" target="_blank">elsewhere on the web</a>, and you can see the process in action in <a href="http://tekpub.com/preview/aspmvc" target="_blank">TekPub’s “Controllers: Part 2” episode</a>, and you’ll find extremely detailed coverage and tutorials into my forthcoming ASP.NET MVC 2.0 book when it’s published. Instead, I’m going to describe one possible way to measure the performance effects of using them, and explain how I learned that <strong>under many default circumstances, you won’t get any benefit from using them unless you make some crucial configuration changes</strong>.</p>
<h4>Measuring Response Times Under Heavy Traffic</h4>
<p>To understand how asynchronous controllers respond to differing levels of traffic, and how this compares to a straightforward synchronous controller, I put together a little ASP.NET MVC 2.0 web application with two controllers. To simulate a long-running external I/O process, they both perform a SQL query that takes 2 seconds to complete (using the SQL command <em>WAITFOR DELAY &#8216;00:00:02&#8242;</em>) and then they return the same fixed text to the browser. One of them does it synchronously; the other asynchronously. </p>
<p>Next, I put together a simple C# console application that simulates heavy traffic hitting a given URL. It simply requests the same URL over and over, calculating the rolling average of the last few response times. First it does so on just one thread, but then gradually increases the number of concurrent threads to 150 over a 30-minute period. If you want to try running this tool against your own site, you can <a href="http://blog.codeville.net/blogfiles/2010/January/LoadTest.zip" target="_blank">download the C# source code</a>.</p>
<p>The results illustrate a number of points about how asynchronous requests perform. Check out this graph of average response times versus number of concurrent requests (lower response times are better):</p>
<p><a href="http://blog.codeville.net/wp-content/uploads/2010/01/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blog.codeville.net/wp-content/uploads/2010/01/image-thumb.png" width="577" height="353" /></a> </p>
<p>To understand this, first I need to tell you that I had set my ASP.NET MVC application’s worker thread pool to an artificially low maximum limit of 50 worker threads. My server actually has a default max threadpool size of 200 – a more sensible limit – but the results are made clearer if I reduce it.</p>
<p>As you can see, the synchronous and asynchronous requests performed exactly the same as long as there were enough worker threads to go around. And why shouldn’t they? </p>
<p>But once the threadpool was exhausted (&gt; 50 clients), the synchronous requests had to form a queue to be serviced. Basic queuing theory tells us that the average time spent waiting in a queue is given by the formula:</p>
<p><a href="http://blog.codeville.net/wp-content/uploads/2010/01/image1.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blog.codeville.net/wp-content/uploads/2010/01/image-thumb1.png" width="560" height="73" /></a> </p>
<p>… and this is exactly what we see in the graph. The queuing time grows linearly with the length of the queue. (Apologies for my indulgence in using a formula – sometimes I just can’t suppress my inner mathematician. I’ll get therapy if it becomes a problem.<em>)</em></p>
<p>The asynchronous requests didn’t need to start queuing so soon, though. They don’t need to block a worker thread while waiting, so the threadpool limit wasn’t an issue. So why did they start queuing when there were more than 100 clients? It’s because the ADO.NET connection pool is limited to 100 concurrent connections by default.</p>
<p>In summary, what can we learn from all this?</p>
<ul>
<li><strong>Asynchronous requests are useful, but *only* if you need to handle more concurrent requests than you have worker threads.</strong> Otherwise, synchronous requests are better just because they let you write simpler code.&#160; <br />(There is an exception: ASP.NET dynamically adjusts the worker thread pool between its minimum and maximum size limits, and if you have a sudden spike in traffic, it can take several minutes for it to notice and create new worker threads. During that time your app may have only a handful of worker threads, and many requests may time out. The reason I gradually adjusted the traffic level over a 30-minute period was to give ASP.NET enough time to adapt. Asynchronous requests are better than synchronous requests at handling sudden traffic spikes, though such spikes don’t happen often in reality.) </li>
<li><strong>Even if you use asynchronous requests, your capacity is limited by the capacity of any external services you rely upon.</strong> Obvious, really, but until you measure it you might not realise how those external services are configured. </li>
<li>It’s not shown on the graph, but <strong>if you have a queue of requests going into ASP.NET, then the queue delay affects *all* requests – not just the ones involving expensive I/O</strong>. This means the entire site feels slow to all users. Under the right circumstances, asynchronous requests can avoid this site-wide slowdown by not forcing the other requests to queue so much. </li>
</ul>
<h4>Gotchas with Configuring for Asynchronous Controllers</h4>
<p>The main surprise I encountered while trying to use asynchronous controllers was that, at first, I couldn’t observe any benefit at all. In fact, it took me almost a whole day of experimentation before I discovered all the things that were preventing them from making a difference. <strong>If I hadn’t been taking measurements, I’d never have known that my asynchronous controller was entirely pointless under default configurations</strong>. For me it’s a reminder that understanding the theory isn’t enough; you have to be able to measure it. </p>
<p>Here are some things you might not have realised:</p>
<ul>
<li><strong>Don’t even bother trying to load test your asynchronous controllers using IIS on Windows XP, Vista, or 7</strong><em>.</em> Under these operating systems, IIS won’t handle more than 10 concurrent requests anyway, so you certainly won’t observe any benefits. </li>
<li><strong>If your application runs under .NET 3.5, you will almost certainly need to change its </strong><a href="http://blogs.msdn.com/tmarq/archive/2007/07/21/asp-net-thread-usage-on-iis-7-0-and-6-0.aspx" target="_blank"><strong>MaxConcurrentRequestsPerCPU setting</strong></a><em>.</em> By default, you’re limited to 12 concurrent requests per CPU – and this includes asynchronous as well as synchronous ones. Under this default setting, there’s no way you can get anywhere near the default worker threadpool limit of 100 per CPU, so you might as well handle everything synchronously. For me this is the biggest surprise; it just seems like a chronic mistake. I’d be interested to know if anyone can explain this. Fortunately, if your app runs under .NET 4, then the MaxConcurrentRequestsPerCPU value is 5000 by default. </li>
<li><strong>If your external I/O operations are HTTP requests (e.g., to a web service), then you may need to </strong><a href="http://blogs.msdn.com/carloc/archive/2008/03/31/maxconnection-does-not-have-effect-on-asp-net-2-0.aspx" target="_blank"><strong>turn off autoConfig</strong></a><strong> and alter your </strong><a href="http://msdn.microsoft.com/en-us/library/7w2sway1.aspx" target="_blank"><strong>maxconnections setting</strong></a><strong> </strong>(either in web.config or machine.config)<strong>.</strong> By default, autoconfig allows for 12 outbound TCP connections per CPU to any given address. That limit might be a little low. </li>
<li><strong>If your external I/O operations are SQL queries, then you may need to change the </strong><a href="http://www.codeproject.com/KB/dotnet/ADONET_ConnectionPooling.aspx" target="_blank"><strong>max ADO.NET connection pool size</strong></a><em>.</em> By default, the limit is 100 in total. Whereas the default ASP.NET worker thread pool limit is 100 <em>per CPU</em>, so you’re likely to hit the connection pool size limit first (unless, I guess, you have less than one CPU…). </li>
</ul>
<p>If you don’t have high capacity requirements – e.g., if you’re building a small intranet application – then you can probably forget all about this blog post and asynchronous controllers in general. Most ASP.NET developers have never heard of asynchronous requests and they get along just fine. </p>
<p>But if you are trying to boost your server’s capacity and think asynchronous controllers are the answer, please be sure to run a practical test and make sure you can observe that your configuration meets your needs.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fblog.codeville.net%2f2010%2f01%2f25%2fmeasuring-the-performance-of-asynchronous-controllers%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fblog.codeville.net%2f2010%2f01%2f25%2fmeasuring-the-performance-of-asynchronous-controllers%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<div class="feedflare">
<a href="http://feeds.codeville.net/~ff/SteveCodeville?a=ex_U-97lKTo:yLWKJhxPvCs:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?i=ex_U-97lKTo:yLWKJhxPvCs:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=ex_U-97lKTo:yLWKJhxPvCs:G79ilh31hkQ"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?d=G79ilh31hkQ" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=ex_U-97lKTo:yLWKJhxPvCs:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?i=ex_U-97lKTo:yLWKJhxPvCs:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.codeville.net/~ff/SteveCodeville?a=ex_U-97lKTo:yLWKJhxPvCs:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/SteveCodeville?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/SteveCodeville/~4/ex_U-97lKTo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.stevensanderson.com/2010/01/25/measuring-the-performance-of-asynchronous-controllers/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.stevensanderson.com/2010/01/25/measuring-the-performance-of-asynchronous-controllers/</feedburner:origLink></item>
	</channel>
</rss>
