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

<channel>
	<title>Ivan Zlatev &#187; Coding</title>
	<atom:link href="http://ivanz.com/category/coding/feed/" rel="self" type="application/rss+xml" />
	<link>http://ivanz.com</link>
	<description></description>
	<lastBuildDate>Mon, 16 Jan 2012 16:11:18 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>dev4good &#8211; Developing for a Better World</title>
		<link>http://ivanz.com/2011/07/04/dev4good-developing-for-a-better-world/</link>
		<comments>http://ivanz.com/2011/07/04/dev4good-developing-for-a-better-world/#comments</comments>
		<pubDate>Mon, 04 Jul 2011 22:44:59 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Diary]]></category>
		<category><![CDATA[Achievements]]></category>
		<category><![CDATA[Charity]]></category>
		<category><![CDATA[Open Source]]></category>

		<guid isPermaLink="false">http://ivanz.com/?p=930</guid>
		<description><![CDATA[<a href="http://ivanz.com/2011/07/04/dev4good-developing-for-a-better-world/" title="dev4good - Developing for a Better World"></a>Last weekend (2-3 July) I attended the first ever dev4good &#8211; a charity hackathon where developers try to solve charity problems in a weekend. It took place in Hammersmith, London in a amazing venue on the riverside: Three charities came &#8230;<p class="read-more"><a href="http://ivanz.com/2011/07/04/dev4good-developing-for-a-better-world/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://ivanz.com/2011/07/04/dev4good-developing-for-a-better-world/" title="dev4good - Developing for a Better World"></a><p><a href="http://ivanz.com/wp-content/uploads/2011/07/charity-portal-screenshot.png" rel="shadowbox[sbpost-930];player=img;"><br />
</a>Last weekend (2-3 July) I attended the first ever <a href="http://dev4good.net">dev4good</a> &#8211; a charity hackathon where developers try to solve charity problems in a weekend. It took place in Hammersmith, London in a amazing venue on the riverside:</p>
<p><a href="http://ivanz.com/wp-content/uploads/2011/07/IMG_1305.jpg" rel="shadowbox[sbpost-930];player=img;"><img class="aligncenter size-large wp-image-945" title="IMG_1305" src="http://ivanz.com/wp-content/uploads/2011/07/IMG_1305-1024x764.jpg" alt="" width="620" height="462" /></a></p>
<p>Three charities came to use with the following problems:</p>
<p><a href="www.hopeandplay.org">Hope and Play</a> were looking for a way to locate and manage resources. And allow other charities or people to do the same.</p>
<p><a href="www.ministryofstories.org">The Ministry of Stories</a> were looking for a way to get more young people writing stories and publishing these to the world. All while helping to generate a little more cash along the way.</p>
<p><a href="www.craftanddesigncouncil.org.uk">The Design and Craft Council</a> want to be able to automate their awards processes.</p>
<p>We were about 25 people and were able to split in three teams. Here is a video of my team explaining what we are planning to achieve for the Hope and Play project (I am the one speaking first):</p>
<p><object width="620" height="490"><param name="movie" value="http://www.youtube.com/v/ml0nhtuA9Bo?version=3"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/ml0nhtuA9Bo?version=3" type="application/x-shockwave-flash" width="620" height="490" allowscriptaccess="always" allowfullscreen="true"></embed></object></p>
<p>Basically we wanted to create a proof of concept system that:</p>
<ol id="internal-source-marker_0.27231994923204184">
<li>Provides a central web portal to aggregate information and also allow charities to communicate what projects they are running, and in which locations.</li>
<li>Allows charities to communicate in real-time work and achievements on their projects via the web portal, Twitter or mobile text messages (SMS).</li>
<li>Enable charities and individuals to advertise their available and required resources (human power, building material, etc) and its location.</li>
<li>Provides a means for charities to discover information on the web relevant to their projects and location.</li>
</ol>
<p>At the end it looked like this (test data, which probably doesn&#8217;t illustrate perfectly the usage):</p>
<p><a href="http://ivanz.com/wp-content/uploads/2011/07/charity-portal-screenshot.png" rel="shadowbox[sbpost-930];player=img;"><img class="aligncenter" title="charity portal screenshot" src="http://ivanz.com/wp-content/uploads/2011/07/charity-portal-screenshot.png" alt="" width="1003" height="841" /></a><br />
My team worked great together. We were able to quickly split the work so that everyone has something of interest to do. It was very exciting to see how we are making progress during our scrum stand ups:<br />
<a href="http://ivanz.com/wp-content/uploads/2011/07/WP_000815.jpg" rel="shadowbox[sbpost-930];player=img;"><img class="aligncenter size-large wp-image-950" title="WP_000815" src="http://ivanz.com/wp-content/uploads/2011/07/WP_000815-1024x768.jpg" alt="" width="620" height="465" /></a><br />
At the start of the event we decided that we are going to use Git for source control and GitHub for hosting. Apart from me only one other person had used Git before, but I was happy to help out each of the guys and keep them going during the event. As you can see from the below GitHub commits timeline we were quite effective in working in parallel:<br />
<a href="http://ivanz.com/wp-content/uploads/2011/07/Weekend-Timeline.png" rel="shadowbox[sbpost-930];player=img;"><img class="aligncenter size-large wp-image-951" title="Weekend Timeline" src="http://ivanz.com/wp-content/uploads/2011/07/Weekend-Timeline-1024x105.png" alt="" width="620" height="63" /></a><br />
I think 99.9% of us were running Windows and using Bash or Cmd was absolutely not an option for the non-Gitters who had mainly experience with TFS or SVN. Most new Gitters used Tortoise Git, but that was still confusing as it required understanding of how everything works. Only later I learned about SmartGit and in retrospect I think we should have used that instead.</p>
<p>As you&#8217;ll hear on the video initially we planned to use Orchard CMS, but after some research and poking around I was personally disappointed to find out how over-complex and over-engineered Orchard is. So we dumped it and went for plain old ASP.NET MVC 3 and non-POCO Entity Framework, which worked out quite well &#8211; after all it was just meant to be proof of concept.</p>
<p>All in all I had great fun during the weekend. I also met some great people, who I am looking forward to seeing and work with again in the future &#8211; probably during GiveCamp UK in October!</p>
<p>At the end of the weekend it turned out that most people voted for me as the most supportive and helpful developer during the weekend, so I won the grand prize &#8211; a Kinect. I wasn&#8217;t expecting this at all and very grateful to everyone and very happy that I was able to help people out. Thanks guys!<br />
<a href="http://ivanz.com/wp-content/uploads/2011/07/Kinect-Prize.jpeg" rel="shadowbox[sbpost-930];player=img;"><img class="aligncenter size-medium wp-image-953" title="Kinect Prize" src="http://ivanz.com/wp-content/uploads/2011/07/Kinect-Prize-300x224.jpg" alt="" width="300" height="224" /></a>And here is an end of event photo of team dev4good:<br />
<a href="http://ivanz.com/wp-content/uploads/2011/07/WP_000825.jpg" rel="shadowbox[sbpost-930];player=img;"><img class="aligncenter size-large wp-image-954" title="WP_000825" src="http://ivanz.com/wp-content/uploads/2011/07/WP_000825-1024x768.jpg" alt="" width="620" height="465" /></a>Great job guys!</p>
<p>Also big thanks to our sponsors:<br />
<a href="http://ivanz.com/wp-content/uploads/2011/07/sponsors.png" rel="shadowbox[sbpost-930];player=img;"><img class="aligncenter size-medium wp-image-955" title="sponsors" src="http://ivanz.com/wp-content/uploads/2011/07/sponsors-300x179.png" alt="" width="300" height="179" /></a></p>
<h3>What&#8217;s next?</h3>
<p>We are in the process of moving and merging the team repositories in a central one in GitHub. I am looking forward to get in touch with some charities to discuss and get feedback for our proof of concept Charity Portal and its eventual real-life practical application.</p>
<p>Next also is GiveCamp UK! I am also tempted to go to Startup Weekend Lonodon, but I&#8217;ll see about that.</p>
 <img src="http://ivanz.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=930" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2011/07/04/dev4good-developing-for-a-better-world/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Featured on the home page of ASP.NET</title>
		<link>http://ivanz.com/2011/07/03/featured-on-the-home-page-of-asp-net/</link>
		<comments>http://ivanz.com/2011/07/03/featured-on-the-home-page-of-asp-net/#comments</comments>
		<pubDate>Sun, 03 Jul 2011 20:28:02 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Diary]]></category>
		<category><![CDATA[Achievements]]></category>

		<guid isPermaLink="false">http://ivanz.com/?p=931</guid>
		<description><![CDATA[<a href="http://ivanz.com/2011/07/03/featured-on-the-home-page-of-asp-net/" title="Featured on the home page of ASP.NET"></a>Really exciting for me is that a few days ago my series on Editing Variable Length Reorderable Collections in ASP.NET MVC got featured on the home page of the ASP.NET web site. I just wanted to say thank you to &#8230;<p class="read-more"><a href="http://ivanz.com/2011/07/03/featured-on-the-home-page-of-asp-net/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://ivanz.com/2011/07/03/featured-on-the-home-page-of-asp-net/" title="Featured on the home page of ASP.NET"></a><p>Really exciting for me is that a few days ago my series on <a href="http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/">Editing Variable Length Reorderable Collections in ASP.NET MVC</a> got featured  on the home page of the ASP.NET web site. I just wanted to say thank you to the person who decided to share it with the community. Here is a screenshot:</p>
<p><a href="http://ivanz.com/wp-content/uploads/2011/07/Ivan-Zlatev-ASP.NET-Home-Page.png" rel="shadowbox[sbpost-931];player=img;"><img src="http://ivanz.com/wp-content/uploads/2011/07/Ivan-Zlatev-ASP.NET-Home-Page.png" alt="" title="Ivan Zlatev ASP.NET Home Page" width="1157" height="1023" class="aligncenter size-full wp-image-932" /></a></p>
 <img src="http://ivanz.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=931" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2011/07/03/featured-on-the-home-page-of-asp-net/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Editing Variable Length Reorderable Collections in ASP.NET MVC &#8211; Part 3: Knockout JS</title>
		<link>http://ivanz.com/2011/06/29/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-3/</link>
		<comments>http://ivanz.com/2011/06/29/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-3/#comments</comments>
		<pubDate>Wed, 29 Jun 2011 16:48:27 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[KnockoutJS]]></category>

		<guid isPermaLink="false">http://ivanz.com/?p=844</guid>
		<description><![CDATA[<a href="http://ivanz.com/2011/06/29/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-3/" title="Editing Variable Length Reorderable Collections in ASP.NET MVC - Part 3: Knockout JS"></a>In Part 1 of this series I discussed the problems that we face when implementing an editor for a variable length, reorderable collection and reuse our server-side ASP.NET MVC views, model binding and validation. In Part 2 of this series &#8230;<p class="read-more"><a href="http://ivanz.com/2011/06/29/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-3/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://ivanz.com/2011/06/29/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-3/" title="Editing Variable Length Reorderable Collections in ASP.NET MVC - Part 3: Knockout JS"></a><p><a title="Editing Variable Length Reorderable Collections in ASP.NET MVC – Part 1" href="http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/">In Part 1 of this series</a> I discussed the problems that we face when implementing an editor for a variable length, reorderable collection and reuse our server-side ASP.NET MVC views, model binding and validation.</p>
<p><a title="Editing Variable Length Reorderable Collections in ASP.NET MVC – Part 2" href="http://ivanz.com/2011/06/20/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-2/">In Part 2 of this series</a> I began moving some aspects of the collection editing to the client-side with jQuery Templates, but we realized that it&#8217;s not good enough, because instead of dealing with data we are juggling with our ASP.NET MVC views generated HTML.</p>
<p>In this final Part 3 of the series I want to move the collection editing completely to the client-side using the <a href="http://knockoutjs.com/">Knockout JS library</a> JavaScript library. I will look at:</p>
<ul>
<li>Knockout JS data-binding and tempalting</li>
<li>JSON Form (data really &#8211; no form) submission</li>
<li>jQuery Client-Side Validation </li>
</ul>
<p>I will re-implement our sample collection editor and it is going to look exactly the same as it did before. Before I begin just a reminder that <a href="http://github.com/ivanz/ASP.NET-MVC-Collection-Editing">all of the source code is available on GitHub as a Visual Studio solution</a>.</p>
<h4>What is Knockout JS?</h4>
<p>I am going to quote its creator (Steven Sanderson) from his introductory post, where he provides <a href="http://blog.stevensanderson.com/2010/07/05/introducing-knockout-a-ui-library-for-javascript/">a very good overview</a>:</p>
<blockquote><p>Knockout 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></blockquote>
<p>I suggest you read the above linked post or checkout the Knockout JS web site to learn more about it, but to quickly summarize how it works:</p>
<ul>
<li>A JavaScipt view model is defined that holds all the data. All the data properties are initialized as (or wrapped in) observable values and arrays.</li>
<li>HTML elements can be data-bound to a property (similar to WinForms/XAML(WPF/Silverlight)) from the view model using the <em>data-bind </em>attribute syntax. We can bind an input&#8217;s value, a span&#8217;s text, etc. to a view model property.</li>
<li>Whenever a value/or array changes the data-binding kicks in and the HTML element are automatically updated.</li>
<li>Knockout uses jQuery and supports templating via jQuery Templates.</li>
</ul>
<h4>Our Sample</h4>
<p>To understand this lets jump straight into our sample app.</p>
<p>I have added a third edit option to our sample:</p>
<p><a href="http://ivanz.com/wp-content/uploads/2011/06/knockout-edit.png" rel="shadowbox[sbpost-844];player=img;"><img class="aligncenter size-full wp-image-856" title="knockout-edit" src="http://ivanz.com/wp-content/uploads/2011/06/knockout-edit.png" alt="" width="304" height="223" /></a></p>
<p>which surprise, surprise looks exactly the same as in the previous iteration. Apart from one extra feature &#8211; the favourite movies counter I&#8217;ve added to give you a hint of the power of Knockout JS:</p>
<p><a href="http://ivanz.com/wp-content/uploads/2011/06/knockout-edit-screen.png" rel="shadowbox[sbpost-844];player=img;"><img class="aligncenter size-full wp-image-857" title="knockout-edit-screen" src="http://ivanz.com/wp-content/uploads/2011/06/knockout-edit-screen.png" alt="" width="571" height="383" /></a></p>
<h4>View and ViewModel</h4>
<p>Let&#8217;s firstly look at the first iteration of our view model implementation:</p>
<pre class="brush: xml; title: ; notranslate">&lt;script type=&quot;text/javascript&quot;&gt;
var viewModel = {
    Id: ko.observable(@Model.Id),
    Name: ko.observable(&quot;@Model.Name&quot;),
    FavouriteMovies: ko.observableArray(@Html.Json(@Model.FavouriteMovies) || []),

    maxMovies: 10,

    addMovie: function() {
        viewModel.FavouriteMovies.push(@Html.Json(new Movie()));
    },

    removeMovie: function(movie) {
        ko.utils.arrayRemoveItem(viewModel.FavouriteMovies, movie);
    }
};

$(function () {
    ko.applyBindings(viewModel);
});
&lt;/script&gt;</pre>
<p>We:</p>
<ul>
<li>Serialize our ASP.NET MVC <em>User</em> Model to JSON (<em>Id</em>, <em>Name</em>, <em>FavouriteMovies</em>). <em>Html.Json</em> is a custom Html helper that simply wraps a JSON serializer &#8211; you can <a href="https://github.com/ivanz/ASP.NET-MVC-Collection-Editing/blob/master/CollectionEditing/Infrastructure/JsonHtmlExtensions.cs">see it in the source code</a>.</li>
<li>Wrap its values in Knockout observables and then once the page is loaded we initialize Knockout JS with our model</li>
<li>Define some add/remove movie methods to edit the FavouriteMovies collection</li>
</ul>
<p><strong>What&#8217;s crucial here is that we are not dealing with nor manipulating HTML markup</strong>, which is something that we were doing heavily in the previous parts.</p>
<p>When processed server-side the above view model will look like roughly like this in the browser:</p>
<pre class="brush: xml; title: ; notranslate">var viewModel = {
        Id: ko.observable(1),
        Name: ko.observable(&quot;Ivan Zlatev&quot;),
        FavouriteMovies: ko.observableArray([{&quot;Title&quot;:&quot;Movie 1&quot;,&quot;Rating&quot;:5},
                                                           {&quot;Title&quot;:&quot;Movie 2&quot;,&quot;Rating&quot;:10},
                                                           {&quot;Title&quot;:&quot;Movie 3&quot;,&quot;Rating&quot;:12}] || []),

        maxMovies: 10,

        addMovie: function() {
            viewModel.FavouriteMovies.push({&quot;Title&quot;:null,&quot;Rating&quot;:0});
        },

        removeMovie: function(movie) {
            ko.utils.arrayRemoveItem(viewModel.FavouriteMovies, movie);
        }
}</pre>
<p>Let&#8217;s look at the first iteration of our edit view (<em>EditKnockoutJS.cshtml</em>) to better understand how does Knockout help us:</p>
<pre class="brush: xml; title: ; notranslate">@model CollectionEditing.Models.User
@{ ViewBag.Title = &quot;Edit My Account With Knockout JS&quot;; }

&lt;script src=&quot;@Url.Content(&quot;~/Scripts/jquery.validate.min.js&quot;)&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;@Url.Content(&quot;~/Scripts/jQuery.tmpl.min.js&quot;)&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;@Url.Content(&quot;~/Scripts/knockout-1.2.1.debug.js&quot;)&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;@Url.Content(&quot;~/Scripts/knockout.jQueryUI-sortable.js&quot;)&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;

&lt;h2&gt;Edit&lt;/h2&gt;

@using (Html.BeginForm(&quot;EditKnockoutJS&quot;, &quot;User&quot;, FormMethod.Post, new { id = &quot;profileEditorForm&quot; })) {
    @Html.ValidationSummary(false)
    &lt;fieldset&gt;
        &lt;legend&gt;My Details&lt;/legend&gt;

        &lt;input name=&quot;userId&quot; type=&quot;hidden&quot; data-bind=&quot;value: Id&quot;/&gt;

        &lt;label for=&quot;name&quot;&gt;Name:&lt;/label&gt;
        &lt;input type=&quot;text&quot; id=&quot;name&quot; name=&quot;name&quot; data-bind=&quot;value: Name&quot; /&gt;
    &lt;/fieldset&gt;

    &lt;fieldset&gt;
        &lt;legend&gt;My Favourite Movies&lt;/legend&gt;

        &lt;ul id=&quot;moviesEditor&quot; style=&quot;list-style-type: none&quot;
            data-bind=&quot;template: { name: 'moviesTemplate', data: FavouriteMovies },
                       sortableList: viewModel.FavouriteMovies&quot; &gt;
        &lt;/ul&gt;
        &lt;p&gt;You have &lt;span data-bind=&quot;text: FavouriteMovies().length&quot;&gt;&lt;/span&gt; favourite movies.&lt;/p&gt;

        &lt;script id=&quot;moviesTemplate&quot; type=&quot;text/x-jquery-template&quot;&gt;
            {{each(i, movie) $data}}
                &lt;li data-bind=&quot;sortableItem: movie&quot;&gt;
                    &lt;div data-bind=&quot;template: { name: 'movieTemplate', data: movie }&quot;&gt;&lt;/div&gt;
                &lt;/li&gt;
            {{/each}}
        &lt;/script&gt;

        &lt;script id=&quot;movieTemplate&quot; type=&quot;text/x-jquery-template&quot;&gt;
            &lt;img src=&quot;@Url.Content(&quot;~/Content/images/draggable-icon.png&quot;)&quot; style=&quot;cursor: move&quot; alt=&quot;&quot;/&gt;

            &lt;label&gt;Title:&lt;/label&gt;
            &lt;input type=&quot;text&quot; data-bind=&quot;value: Title&quot;/&gt;

            &lt;label&gt;Rating:&lt;/label&gt;
            &lt;input type=&quot;text&quot; data-bind=&quot;value: Rating&quot;/&gt;

            &lt;a href=&quot;#&quot; data-bind=&quot;click: function() { viewModel.removeMovie(this); }&quot;&gt;Delete&lt;/a&gt;
        &lt;/script&gt;

        &lt;button data-bind=&quot;click: addMovie, enable: FavouriteMovies().length &lt; maxMovies&quot;&gt;Add another&lt;/button&gt;
    &lt;/fieldset&gt;

    &lt;p&gt;
        &lt;input type=&quot;submit&quot; value=&quot;Save&quot; /&gt;
        &lt;a href=&quot;/&quot;&gt;Cancel&lt;/a&gt;
    &lt;/p&gt;
}</pre>
<p>In our view we use Knockout JS to data-bind our HTML input fields to the data in the viewModel (notice the &#8220;<em>data-bind</em>&#8221; attributes).</p>
<p>For the collection editor:</p>
<ul>
<li>Similar to Part 2, we have a movie jQuery template, which defines the HTML fields of a movie, but this time we don&#8217;t use any ASP.NET MVC helpers.</li>
<li>We make the HTML list reorderable via Drag and Drop with the two special <em>sortableList</em> and <em>sortableItem</em> bindings.This is a custom Knockout JS binding I&#8217;ve created and hosted on <a href="https://github.com/ivanz/knockout.jQueryUI-sortable.js/blob/master/knockout.jQueryUI-sortable.js">GitHub here</a>. Behind the scenes it magically creates a JQuery UI Sortable keeps our <em>viewModel.FavouriteMovies</em> collection in sync when the widget changes.</li>
<li>We limit the number of favourite movies a user can add via the &#8220;Add Another&#8221; button to ten by using a &#8220;<em>enabled</em>&#8221; binding with a boolean expression. Behind the scenes Knockout JS will manage the state of the button and toggle between enabled/disabled depending on the evaluated value of the expression.</li>
<li>Finally we data-bind a <em>span</em> element to display the current number of favourite movies the user has added. Again, this is something that Knockout will keep up to date for us.</li>
</ul>
<p>Right now with this viewModel and that view we have a working drag and drop add/remove favourite movies editor. What we are still missing however is:</p>
<ul>
<li>Form submission and server-side handling</li>
<li>Form validation</li>
</ul>
<h4>Form Submission and Handling</h4>
<p>Let&#8217;s add some more code to our view model and view to handle form submission.</p>
<p>Firstly we are going to implement a save function in our view model. Because we are no longer using ASP.NET model views, we can&#8217;t simply submit the form as is &#8211; the &#8220;standard&#8221; form values based ASP.NET MVC model binding won&#8217;t work properly and especially so for the collection editing part. </p>
<p>Thankfully starting from version 3 ASP.NET MVC supports out of the box JSON model binding. It kicks in if the HTTP request Content-Type is set to &#8220;application/json&#8221;. So instead of using form submission we are going to post our view model data via an AJAX post request to our MVC action, containing the data in JSON serialized form:</p>
<pre class="brush: jscript; title: ; notranslate"> var viewModel = {
       ... snip ...

        saveFailed: ko.observable(false),

        // Returns true if successful
        save: function()
        {
            var saveSuccess = false;
            viewModel.saveFailed(false);

            // Executed synchronously for simplicity
            jQuery.ajax({
                type: &quot;POST&quot;,
                url: &quot;@Url.Action(&quot;EditKnockoutJS&quot;, &quot;User&quot;)&quot;,
                data: ko.toJSON(viewModel),
                dataType: &quot;json&quot;,
                contentType: &quot;application/json&quot;,
                success: function(returnedData) {
                    saveSuccess = returnedData.Success || false;
                    viewModel.saveFailed(!saveSuccess);
                },
                async: false
            });

            return saveSuccess;
        }
};</pre>
<p>Then we will suppress the default form submission behaviour and replace it with our own:</p>
<pre class="brush: xml; title: ; notranslate">&lt;p&gt;
    &lt;input type=&quot;submit&quot; value=&quot;Save&quot;
             data-bind=&quot;click: function() { viewModel.save(); return false; }&quot;/&gt;
    &lt;a href=&quot;/&quot;&gt;Cancel&lt;/a&gt;
&lt;/p&gt;

&lt;p data-bind=&quot;visible: saveFailed&quot; class=&quot;error&quot;&gt;A problem occurred saving the data.&lt;/p&gt;</pre>
<p>Note that I have added a new &#8220;<em>saveFailed</em>&#8221; property in the viewModel which is set by <em>save()</em>. I have also used a &#8220;<em>visible</em>&#8221; data binding on the value of that property to display the error message paragraph only if the save operation has failed.</p>
<p>Now let&#8217;s also look at the MVC action to handle the form submission:</p>
<pre class="brush: csharp; title: ; notranslate">
[HttpPost]
public ActionResult EditKnockoutJS(User user)
{
    FormResponseData responseData = new FormResponseData() {
        Success = false
    };

    if (this.ModelState.IsValid) {
        CurrentUser = user;
        responseData.Success = true;
    }

    return Json(responseData);
}

class FormResponseData {
    public bool Success { get; set; }
}</pre>
<p>Pretty simple action, which just validates the Model using our validation rules/data annotations and returns a <em>FormReponseData</em> object serialized to JSON, which contains a Success flag expected by the client side.</p>
<p>We can now persist our view model and also use our server-side model validation to prevent the client from doing nasty things:</p>
<p><a href="http://ivanz.com/wp-content/uploads/2011/06/knockout-edit-server-validation.png" rel="shadowbox[sbpost-844];player=img;"><img src="http://ivanz.com/wp-content/uploads/2011/06/knockout-edit-server-validation.png" alt="" title="knockout-edit-server-validation" width="558" height="207" class="aligncenter size-full wp-image-905" /></a></p>
<p>We are not done just yet. Because we no longer use the ASP.NET html helpers we no longer pull the server-side validation error messages and are currently left with the generic &#8220;Something went wrong.&#8221; error message. This isn&#8217;t exactly nice nor user friendly. We can solve this by the use of client-side JavaScript based validation. Remember that we should never ever rely solely on the client-side (and we don&#8217;t in our case).</p>
<h4>Client-Side Validation</h4>
<p>Unfortunately at the time of writing I couldn&#8217;t find anything that validates against the Knockout JS viewModel instead of the HTML markup, so I had to resort to <a href="http://docs.jquery.com/Plugins/validation">jQuery Validation</a> for the client-side validation. The problem with that is that we need to ensure that we have set proper unique &#8220;name&#8221; attributes on our form fields and especially so for our collection editor elements.</p>
<p>Fortunately Knockout JS already has a binding for that called the &#8220;<em>uniqueName</em> binding&#8221;, so all we have to do is add that to our favourite movie collection editor fields like I&#8217;ve showed below and don&#8217;t worry about generating them ourselves. This is great, because as you saw in Part 2 injecting a unique name during jQuery template evaluation is relatively tricky.</p>
<pre class="brush: xml; title: ; notranslate">&lt;script id=&quot;movieTemplate&quot; type=&quot;text/x-jquery-template&quot;&gt;
    &lt;img src=&quot;@Url.Content(&quot;~/Content/images/draggable-icon.png&quot;)&quot; style=&quot;cursor: move&quot; alt=&quot;&quot;/&gt;

    &lt;label&gt;Title:&lt;/label&gt;
    &lt;input type=&quot;text&quot; data-bind=&quot;value: Title, uniqueName: true&quot; class=&quot;required&quot;/&gt;

    &lt;label&gt;Rating:&lt;/label&gt;
    &lt;input type=&quot;text&quot; data-bind=&quot;value: Rating, uniqueName: true&quot; class=&quot;required&quot;/&gt;

    &lt;a href=&quot;#&quot; data-bind=&quot;click: function() { viewModel.removeMovie(this); }&quot;&gt;Delete&lt;/a&gt;
&lt;/script&gt;</pre>
<p>There are multiple ways we can use jQuery Validation and I have decided to go for the simplest declarative one, where we decorate our fields with extra attributes to describe the value constraints that we want to enforce. Let&#8217;s update the above fields to make the <em>Title</em> and <em>Rating</em> required:</p>
<pre class="brush: xml; title: ; notranslate">&lt;label&gt;Title:&lt;/label&gt;
&lt;input type=&quot;text&quot; data-bind=&quot;value: Title, uniqueName: true&quot; class=&quot;required&quot;/&gt;

&lt;label&gt;Rating:&lt;/label&gt;
&lt;input type=&quot;text&quot; data-bind=&quot;value: Rating, uniqueName: true&quot; class=&quot;required&quot;/&gt;</pre>
<p>Finally let&#8217;s plug-in jQuery Validation. To do that we will remove the previous submit button handler and use jQuery Validation instead:</p>
<pre class="brush: xml; title: ; notranslate">
... snip... 

        &lt;input type=&quot;submit&quot; value=&quot;Save&quot;/&gt;

... snip... 

&lt;script type=&quot;text/javascript&quot;&gt;
    $(function () {
        ko.applyBindings(viewModel);

        $(&quot;#profileEditorForm&quot;).validate({
            submitHandler: function(form) {
                if(viewModel.save())
                    window.location.href = &quot;/&quot;;

                return false;
            }
        });
    });
&lt;/script&gt;</pre>
<p>Which gives us nice per-field validation error messages as we type:</p>
<p><a href="http://ivanz.com/wp-content/uploads/2011/06/knockout-edit-client-validation.png" rel="shadowbox[sbpost-844];player=img;"><img src="http://ivanz.com/wp-content/uploads/2011/06/knockout-edit-client-validation.png" alt="" title="knockout-edit-client-validation" width="676" height="276" class="aligncenter size-full wp-image-909" /></a></p>
<h4>Wrapping up</h4>
<p><a href="http://github.com/ivanz/ASP.NET-MVC-Collection-Editing">Download all of the source code from GitHub as a Visual Studio solution.</a></p>
<p>In this part we looked at Knockout JS and how great it is in terms of helping us avoid manipulation of HTML markup among many other things. This is generally something that can get really messy quickly and become hard to maintain and track. We also looked at how it helps us neatly solve our collection editing problem without having to worry about practically anything. In the expense of the sacrifice of our Html helpers and partial views, etc we get a lot of flexibility on the client side to add more interactivity in a neat and clean way.</p>
<h4>Final Words</h4>
<p>If you have a simple collection editing scenario and you are heavily reliant on your ASP.NET MVC views, partial views, editors and displays the approach documented in <a href="http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/">Part 1</a> should be sufficient. And if pulling in new entries/rows via AJAX is not an option (e.g. for speed, performance or any other reasons) you can pull in <a href="http://ivanz.com/2011/06/20/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-2/">Part 2</a>. However IMHO the better solution most of the time is to use Knockout JS and what I have described in this part as it opens the doors for more complex client-side interactions in a neat and clean way.</p>
<p>Thank you for reading the series. I will appreciate your feedback in the comments!</p>
 <img src="http://ivanz.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=844" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2011/06/29/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-3/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Custom Knockout JS binding for jQuery UI Sortable</title>
		<link>http://ivanz.com/2011/06/27/custom-knockout-js-binding-for-jquery-ui-sortable/</link>
		<comments>http://ivanz.com/2011/06/27/custom-knockout-js-binding-for-jquery-ui-sortable/#comments</comments>
		<pubDate>Mon, 27 Jun 2011 20:23:24 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[KnockoutJS]]></category>

		<guid isPermaLink="false">http://ivanz.com/?p=865</guid>
		<description><![CDATA[<a href="http://ivanz.com/2011/06/27/custom-knockout-js-binding-for-jquery-ui-sortable/" title="Custom Knockout JS binding for jQuery UI Sortable"></a>For the work in progress Part 3 of my Editing Variable Length Reorderable Collections in ASP.NET MVC blog series I have created a custom Knockout JS binding that keeps a Knockout JS observable array in sync with a jQuery UI &#8230;<p class="read-more"><a href="http://ivanz.com/2011/06/27/custom-knockout-js-binding-for-jquery-ui-sortable/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://ivanz.com/2011/06/27/custom-knockout-js-binding-for-jquery-ui-sortable/" title="Custom Knockout JS binding for jQuery UI Sortable"></a><p>For the work in progress Part 3 of my <a href="http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/">Editing Variable Length Reorderable Collections in ASP.NET MVC</a> blog series I have created a custom Knockout JS binding that keeps a Knockout JS observable array in sync with a jQuery UI sortable.</p>
<p>It&#8217;s available here:</p>
<p>Basic usage is to use a <em>sortableList</em> binding on the <em>ul</em> which you  want to make a jQuery Sortable and then a <em>sortableItem</em> binding for each sortable item (<em>li</em>) in the list like that: </p>
<pre class="brush: xml; title: ; notranslate">&lt;ul data-bind=&quot;sortableList: yourObservableArray&quot; &gt;
    {{each(i, arrayItem) yourObservableArray}}
        &lt;li data-bind=&quot;sortableItem: arrayItem&quot;&gt;&lt;/li&gt;
    {{/each}}
&lt;/ul&gt;</pre>
<p>Live example (if you are reading this in a feed reader you will need to open the blog post properly to see this):</p>

<!-- powered by Iframe plugin ver.2.1 (wordpress.org/extend/plugins/iframe/) -->
<iframe src="http://ivanz.github.com/knockout.jQueryUI-sortable.js/example.html" width="100%" height="400" scrolling="no" class="iframe-class" frameborder="0"></iframe>
 <img src="http://ivanz.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=865" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2011/06/27/custom-knockout-js-binding-for-jquery-ui-sortable/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Editing Variable Length Reorderable Collections in ASP.NET MVC – Part 2: jQuery Templates</title>
		<link>http://ivanz.com/2011/06/20/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-2/</link>
		<comments>http://ivanz.com/2011/06/20/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-2/#comments</comments>
		<pubDate>Mon, 20 Jun 2011 19:21:44 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://ivanz.com/?p=796</guid>
		<description><![CDATA[<a href="http://ivanz.com/2011/06/20/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-2/" title="Editing Variable Length Reorderable Collections in ASP.NET MVC – Part 2: jQuery Templates"></a>In Part 1 of this series I discussed the problems that we face when implementing an editor for a variable length, reorderable collection and reuse our server-side ASP.NET MVC views, model binding and validation. And while the solution provided in Part &#8230;<p class="read-more"><a href="http://ivanz.com/2011/06/20/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-2/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://ivanz.com/2011/06/20/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-2/" title="Editing Variable Length Reorderable Collections in ASP.NET MVC – Part 2: jQuery Templates"></a><p><a title="Editing Variable Length Reorderable Collections in ASP.NET MVC – Part 1" href="http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/">In Part 1 of this series</a> I discussed the problems that we face when implementing an editor for a variable length, reorderable collection and reuse our server-side ASP.NET MVC views, model binding and validation. And while the solution provided in Part 1 is nice and clean (and I personally use it in a few projects) one field for improvement in true Agile Blogging fashion is to find a way to remove the AJAX request we use for fetching new editor rows.</p>
<p>One way to bring this completely to the client side is by the use of <a href="http://api.jquery.com/category/plugins/templates/">jQuery Template</a> (or any other JavaScript templating engine/library).</p>
<p>A reminder of what our editor looks like before I begin and a second remind that the source code is available on <a href="http://github.com/ivanz/ASP.NET-MVC-Collection-Editing">GitHub</a>:</p>
<p><a href="http://ivanz.com/wp-content/uploads/2011/06/image3.png" rel="shadowbox[sbpost-796];player=img;"><img class="size-full wp-image-780 aligncenter" title="Sample Editor" src="http://ivanz.com/wp-content/uploads/2011/06/image3.png" alt="" width="550" height="435" /></a></p>
<p>To start with I have added a second link to our sample&#8217;s home page titled &#8220;Edit with jQuery templates&#8221;:</p>
<p><a href="http://ivanz.com/wp-content/uploads/2011/06/home-jquery.png" rel="shadowbox[sbpost-796];player=img;"><img class="aligncenter size-full wp-image-803" title="Home Page of the sample" src="http://ivanz.com/wp-content/uploads/2011/06/home-jquery.png" alt="" width="298" height="202" /></a></p>
<p>Corresponding controller actions:</p>
<pre class="brush: csharp; title: ; notranslate">
public ActionResult EditJQueryTemplate()
{
    return View(CurrentUser);
}

[HttpPost]
public ActionResult EditJQueryTemplate(User user)
{
    if (!this.ModelState.IsValid)
        return View(user);

    CurrentUser = user;
    return RedirectToAction(&quot;Display&quot;);
}</pre>
<p>And a new editor view (<em>EditJQueryTemplate.cshtml</em>) which is exactly the same as the one from Part 1 apart from the core editor bit:</p>
<pre class="brush: xml; highlight: [16,26]; title: ; notranslate">&lt;legend&gt;My Favourite Movies&lt;/legend&gt;

@if (Model.FavouriteMovies == null || Model.FavouriteMovies.Count == 0) {
    &lt;p&gt;None.&lt;/p&gt;
}
&lt;ul id=&quot;moviesEditor&quot; style=&quot;list-style-type: none&quot;&gt;
    @if (Model.FavouriteMovies != null) {
        foreach (Movie movie in Model.FavouriteMovies) {
            Html.RenderPartial(&quot;MovieEntryEditor&quot;, movie);
        }
    }
&lt;/ul&gt;
&lt;script src=&quot;@Url.Content(&quot;~/Scripts/jQuery.tmpl.min.js&quot;)&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;

&lt;script type=&quot;text/x-jquery-tmpl&quot; id=&quot;movieTemplate&quot;&gt;
    @Html.CollectionItemJQueryTemplate(&quot;MovieEntryEditor&quot;, new Movie())
&lt;/script&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
    $(function () {
        $(&quot;#moviesEditor&quot;).sortable();
    });

    var viewModel = {
        addNew: function () {
            $(&quot;#moviesEditor&quot;).append($(&quot;#movieTemplate&quot;).tmpl({ index: viewModel._generateGuid() }));
        },

        _generateGuid: function () {
            // Source: http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/105074#105074
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r &amp; 0x3 | 0x8);
                return v.toString(16);
            });
        }
    };
&lt;/script&gt;

&lt;a id=&quot;addAnother&quot; href=&quot;#&quot; onclick=&quot;viewModel.addNew();&quot;&gt;Add another&lt;/a&gt;</pre>
<p>Note the new <em>@Html.CollectionItemJQueryTemplate</em> helper, which takes a collection item instance with default values and the unchanged partial view <em>MovieEntryEditor</em> from Part 1:</p>
<pre class="brush: xml; title: ; notranslate">@model CollectionEditing.Models.Movie

&lt;li style=&quot;padding-bottom:15px&quot;&gt;
    @using (Html.BeginCollectionItem(&quot;FavouriteMovies&quot;)) {
        &lt;img src=&quot;@Url.Content(&quot;~/Content/images/draggable-icon.png&quot;)&quot; style=&quot;cursor: move&quot; alt=&quot;&quot;/&gt;

        @Html.LabelFor(model =&gt; model.Title)
        @Html.EditorFor(model =&gt; model.Title)
        @Html.ValidationMessageFor(model =&gt; model.Title)

        @Html.LabelFor(model =&gt; model.Rating)
        @Html.EditorFor(model =&gt; model.Rating)
        @Html.ValidationMessageFor(model =&gt; model.Rating)

        &lt;a href=&quot;#&quot; onclick=&quot;$(this).parent().remove();&quot;&gt;Delete&lt;/a&gt;
    }
&lt;/li&gt;
</pre>
<p>Basically the helper renders the partial with an ${$index} jQuery template placeholder for which we supply a GUID at run-time on the client-side when we render the template. The output of the helper looks like this:</p>
<pre class="brush: xml; title: ; notranslate">&lt;script type=&quot;text/x-jquery-tmpl&quot; id=&quot;movieTemplate&quot;&gt;
&lt;li style=&quot;padding-bottom:15px&quot;&gt;

    &lt;input autocomplete=&quot;off&quot; name=&quot;FavouriteMovies.Index&quot; type=&quot;hidden&quot; value=&quot;${index}&quot; /&gt;

    &lt;img src=&quot;/Content/images/draggable-icon.png&quot; style=&quot;cursor: move&quot; alt=&quot;&quot;/&gt;

    &lt;label&gt;Title&lt;/label&gt;
    &lt;input name=&quot;FavouriteMovies[${index}].Title&quot; type=&quot;text&quot; value=&quot;&quot; /&gt;

    &lt;label&gt;Rating&lt;/label&gt;
    &lt;input name=&quot;FavouriteMovies[${index}].Rating&quot; type=&quot;text&quot; value=&quot;0&quot; /&gt;

    &lt;a href=&quot;#&quot; onclick=&quot;$(this).parent().remove();&quot;&gt;Delete&lt;/a&gt;
&lt;/li&gt;
&lt;/script&gt;</pre>
<p>Everytime the &#8220;Add another&#8221; button is pressed this template is rendered using a new GUID index value supplied by the <em>viewModel</em> class.</p>
<p>Here is the code of the <em>@Html.CollectionItemJQueryTemplate</em> helper:</p>
<pre class="brush: csharp; title: ; notranslate">public static MvcHtmlString CollectionItemJQueryTemplate&lt;TModel, TCollectionItem&gt;(this HtmlHelper&lt;TModel&gt; html,
                                                                                    string partialViewName,
                                                                                    TCollectionItem modelDefaultValues)
{
    ViewDataDictionary&lt;TCollectionItem&gt; viewData = new ViewDataDictionary&lt;TCollectionItem&gt;(modelDefaultValues);
    viewData.Add(JQueryTemplatingEnabledKey, true);
    return html.Partial(partialViewName, modelDefaultValues, viewData);
}</pre>
<p>It renders the supplied partial view, but before that it sets a flag on the ViewContext&#8217;s ViewData dictionary to indicate that the view is to be rendered as jQuery collection item template. This is then handled by the <em>@Html.BeginCollectionItem</em> by generating an index template placeholder based .Index hidden field for model binding instead of one with an actual GUID value:</p>
<pre class="brush: csharp; title: ; notranslate">public static IDisposable BeginCollectionItem&lt;TModel&gt;(this HtmlHelper&lt;TModel&gt; html, string collectionName)
{
    string collectionIndexFieldName = String.Format(&quot;{0}.Index&quot;, collectionName);

    string itemIndex = null;
    if (html.ViewData.ContainsKey(JQueryTemplatingEnabledKey)) {
        itemIndex = &quot;${index}&quot;;
    } else {
        itemIndex = GetCollectionItemIndex(collectionIndexFieldName);
    }

    string collectionItemName = String.Format(&quot;{0}[{1}]&quot;, collectionName, itemIndex);

    TagBuilder indexField = new TagBuilder(&quot;input&quot;);
    indexField.MergeAttributes(new Dictionary&lt;string, string&gt;() {
        { &quot;name&quot;, collectionIndexFieldName },
        { &quot;value&quot;, itemIndex },
        { &quot;type&quot;, &quot;hidden&quot; },
        { &quot;autocomplete&quot;, &quot;off&quot; }
    });
// snip---</pre>
<p>That&#8217;s it! We are still reusing our ASP.NET views, model binding and validation, but no longer require an AJAX request to fetch a new editor row!.</p>
<p>In Part 3 I will look at Knockout JS templating, data binding and moving variable length reorderable collection editing completely on the client side with the MVVM pattern and using JavaScript form serialization and JSON data submission and model binding.</p>
<p><strong>Next: <a href="http://ivanz.com/2011/06/29/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-3/">Part 3 and Knockout JS client-side collection editing, JSON model binding and client-side validation.</a></strong></p>
 <img src="http://ivanz.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=796" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2011/06/20/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-2/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Editing Variable Length Reorderable Collections in ASP.NET MVC &#8211; Part 1: ASP.NET MVC Views</title>
		<link>http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/</link>
		<comments>http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/#comments</comments>
		<pubDate>Thu, 16 Jun 2011 19:46:37 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>

		<guid isPermaLink="false">http://ivanz.com/?p=786</guid>
		<description><![CDATA[<a href="http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/" title="Editing Variable Length Reorderable Collections in ASP.NET MVC - Part 1: ASP.NET MVC Views"></a>Introduction I have decided to write a short series of blog posts on editing collections and more specifically variable length collections in ASP.NET MVC. I will take two different implementation approaches: In Part 1 I look at implementing collection editing &#8230;<p class="read-more"><a href="http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/" title="Editing Variable Length Reorderable Collections in ASP.NET MVC - Part 1: ASP.NET MVC Views"></a><h3>Introduction</h3>
<p>I have decided to write a short series of blog posts on editing collections and more specifically variable length collections in ASP.NET MVC. I will take two different implementation approaches:</p>
<ol>
<li><a href="http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/">In <strong>Part 1</strong></a> I look at implementing collection editing by sticking to facilities provided to us by ASP.NET MVC such as views, partial views, editor templates, model binding, model validation, etc.</li>
<li><a href="http://ivanz.com/2011/06/20/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-2/">In <strong>Part 2</strong></a> I further enhance the sample by using jQuery Templates, but still utilize the same ASP.NET MVC views from Part 1.</li>
<li><a href="http://ivanz.com/2011/06/29/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-3/">In <strong>Part 3</strong></a> I will look at Knockout JS templating, data binding and moving variable length reorderable collection editing completely on the client side with the MVVM pattern and  JSON data submission and model binding.</li>
</ol>
<p>The aspects I will consider are:</p>
<ul>
<li>Dynamically adding, removing and reordering items to/from the collection</li>
<li>Validation implications</li>
<li>Code Reusability and Refactoring implications</li>
</ul>
<p>I will assume that you are already familiar with ASP.NET MVC and basic JavaScript concepts.</p>
<h3>Source Code</h3>
<p><a href="http://github.com/ivanz/ASP.NET-MVC-Collection-Editing" target="_blank">All source code is available on GitHub</a></p>
<h3>The Sample</h3>
<p>What I am going to build is a little sample where we have a user who has a list of favourite movies. It will look roughly like on the image below and will allow for adding new favourite movies, removing favourite movies and also reordering them up and down using the drag handler.</p>
<p><a href="http://ivanz.com/wp-content/uploads/2011/06/image3.png" rel="shadowbox[sbpost-786];player=img;"><img style="background-image: none; margin: 10px auto; padding-left: 0px; padding-right: 0px; display: block; float: none; padding-top: 0px; border-width: 0px;" title="image" src="http://ivanz.com/wp-content/uploads/2011/06/image_thumb3.png" border="0" alt="image" width="554" height="439" /></a></p>
<h3>Domain Model</h3>
<p>The domain model is basically:</p>
<p>
<pre class="brush: csharp; title: ; notranslate">public class User
{
    public int? Id { get; set; }
    [Required]
    public string Name { get; set; }
    public IList&lt;Movie&gt; FavouriteMovies { get; set; }
}</pre>
</p>
<p>and</p>
<p>
<pre class="brush: csharp; title: ; notranslate">public class Movie
{
    [Required]
    public string Title { get; set; }
    public int Rating { get; set; }
}</pre>
</p>
<p>Let’s get cracking!</p>
<h3>An Edit View</h3>
<p>Let’s start by creating a first-pass edit view for our Person to look like the one on the image above:</p>
<p>
<pre class="brush: xml; title: ; notranslate">@model CollectionEditing.Models.User
@{ ViewBag.Title = &quot;Edit My Account&quot;; }

&lt;h2&gt;Edit&lt;/h2&gt;

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    &lt;fieldset&gt;
        &lt;legend&gt;My Details&lt;/legend&gt;

        @Html.HiddenFor(model =&gt; model.Id)

        &lt;div class=&quot;editor-label&quot;&gt;
            @Html.LabelFor(model =&gt; model.Name)
        &lt;/div&gt;
        &lt;div class=&quot;editor-field&quot;&gt;
            @Html.EditorFor(model =&gt; model.Name)
            @Html.ValidationMessageFor(model =&gt; model.Name)
        &lt;/div&gt;
    &lt;/fieldset&gt;

    &lt;fieldset&gt;
        &lt;legend&gt;My Favourite Movies&lt;/legend&gt;

        @if (Model.FavouriteMovies == null || Model.FavouriteMovies.Count == 0) {
            &lt;p&gt;None.&lt;/p&gt;
        } else {
            &lt;ul id=&quot;movieEditor&quot; style=&quot;list-style-type: none&quot;&gt;
                @for (int i=0; i &lt; Model.FavouriteMovies.Count; i++) {
                    &lt;li style=&quot;padding-bottom:15px&quot;&gt;
                        &lt;img src=&quot;@Url.Content(&quot;~/Content/images/draggable-icon.png&quot;)&quot; style=&quot;cursor: move&quot; alt=&quot;&quot;/&gt;

                        @Html.LabelFor(model =&gt; model.FavouriteMovies[i].Title)
                        @Html.EditorFor(model =&gt; model.FavouriteMovies[i].Title)
                        @Html.ValidationMessageFor(model =&gt; model.FavouriteMovies[i].Title)

                        @Html.LabelFor(model =&gt; model.FavouriteMovies[i].Rating)
                        @Html.EditorFor(model =&gt; model.FavouriteMovies[i].Rating)
                        @Html.ValidationMessageFor(model =&gt; model.FavouriteMovies[i].Rating)

                        &lt;a href=&quot;#&quot; onclick=&quot;$(this).parent().remove();&quot;&gt;Delete&lt;/a&gt;
                    &lt;/li&gt;
                }
            &lt;/ul&gt;
            &lt;a href=&quot;#&quot;&gt;Add another&lt;/a&gt;
        }

        &lt;script type=&quot;text/javascript&quot;&gt;
            $(function () {
                $(&quot;#movieEditor&quot;).sortable();
            });
        &lt;/script&gt;
    &lt;/fieldset&gt;

    &lt;p&gt;
        &lt;input type=&quot;submit&quot; value=&quot;Save&quot; /&gt;
        &lt;a href=&quot;/&quot;&gt;Cancel&lt;/a&gt;
    &lt;/p&gt;
}</pre>
</p>
<p>The view is creating a list of editing controls for each of the movies in <em>Person.FavouriteMovies</em>. I am using a jQuery selector and dom function to remove a movie when the user clicks “Delete”  and also a <a href="http://jqueryui.com/demos/sortable/" target="_blank">jQuery UI Sortable</a> to make the items from the HTML list drag and droppable up and down.</p>
<p>With this done we immediately face the first problem: <span style="text-decoration: underline;">We haven’t implemented the “Add another”</span>. Before we do that let’s consider how ASP.NET MVC model binding of collections works.</p>
<h3>ASP.NET MVC Collection Model Binding Patterns</h3>
<p>There are two patterns for model binding collections in ASP.NET MVC. The <strong>first one</strong> you have just seen:</p>
<p>
<pre class="brush: xml; title: ; notranslate">@for (int i=0; i &lt; Model.FavouriteMovies.Count; i++) {
    @Html.LabelFor(model =&gt; model.FavouriteMovies[i].Title)
    @Html.EditorFor(model =&gt; model.FavouriteMovies[i].Title)
    @Html.ValidationMessageFor(model =&gt; model.FavouriteMovies[i].Title)
…
}</pre>
</p>
<p>which generates similar HTML:</p>
<pre class="brush: xml; title: ; notranslate">&lt;label for=&quot;FavouriteMovies_0__Title&quot;&gt;Title&lt;/label&gt;
&lt;input id=&quot;FavouriteMovies_0__Title&quot; name=&quot;FavouriteMovies[0].Title&quot; type=&quot;text&quot; value=&quot;&quot; /&gt;
&lt;span class=&quot;field-validation-error&quot;&gt;The Title field is required.&lt;/span&gt;</pre>
</p>
<p>This is really great for displaying collections and editing static length collections, but problematic when we want to edit variable length collections, because:</p>
<ol>
<li><strong>Indices have to be sequential (0, 1, 2, 3, …). If they aren’t ASP.NET MVC stops at the first gap. E.g. if you have item 0, 1, 3, 4 after the model binding has finished you will end up with a collection of two items only – 1 and 2 instead of four items.</strong></li>
<li><strong>If you were to reorder the list in the HTML ASP.NET MVC will apply the indices order not the fields order when doing model binding.</strong></li>
</ol>
<p>This basically means that add/remove/reorder scenarios are no go with this. It’s not impossible but it will be big big mess tracking add/remove/reorder actions and re-indexing all field attributes.</p>
<p>Now, someone might say – “<em>Hey, why don’t you just implement a non-sequential collection model binder?”</em> .</p>
<p>Yes, you can write the code for a non-sequential collection model binder. You will however face two major issues with that however. The first being that the <em>IValueProvider</em> doesn’t expose a way to iterate through all values in the <em>BindingContext</em> which you can workaround<em> </em>by hardcoding the model binder to access the current HttpRequest Form values collection (meaning that if someone decides to submit the form via Json or query parameters your model binder won’t work) or I’ve seen one more insane workaround which checks the <em>BindingContext</em> one by one from <em>CollectionName[0]</em> to <em>CollectionName[Int32.MaxValue]</em> (that’s <span style="text-decoration: underline;">2 billion</span> iterations!).</p>
<p>Second major issue is that once you create a sequential collection from the non-sequential indices and items and you have a validation error and you re-render the form view your ModelState will no longer match the data. An item that used to be at index X is now at index X-1 after another item before it was deleted, however the ModelState validation message and state still point to X, because this is what you submitted.</p>
<p>So, even a custom model binder won’t help.</p>
<p>Thankfully there is a <strong>second pattern</strong>, which mostly helps for what we want to achieve (even though I don’t think it was designed to solve exactly this):</p>
<pre class="brush: xml; title: ; notranslate">&lt;input type=&quot;hidden&quot; name=&quot;FavouriteMovies.Index&quot; value=&quot;indexA&quot;/&gt;
&lt;input name=&quot;FavouriteMovies[indexA].Title&quot; type=&quot;text&quot; value=&quot;&quot; /&gt;
&lt;input name=&quot;FavouriteMovies[indexA].Rating&quot; type=&quot;text&quot; value=&quot;&quot; /&gt;
&lt;input type=&quot;hidden&quot; name=&quot;FavouriteMovies.Index&quot; value=&quot;indexB&quot;/&gt;
&lt;input name=&quot;FavouriteMovies[indexB].Title&quot; type=&quot;text&quot; value=&quot;&quot; /&gt;
&lt;input name=&quot;FavouriteMovies[indexB].Rating&quot; type=&quot;text&quot; value=&quot;&quot; /&gt;</pre>
</p>
<p>Notice how we have introduced an “.Index” hidden field for each collection item. By doing that we tell ASP.NET MVC’s model binding “Hey, don’t look for a standard numeric collection index, but instead look for the custom Index value we have specified and just get me the list of items in a collection when you are done”. How does this help?</p>
<ol>
<li>We can specify any index value we want</li>
<li>The index doesn’t have to be sequential and items will be put in the collection in the order they are in the HTML when submitted.</li>
</ol>
<p>Bam! That’s solves most, but not all of our problems.</p>
<h3>The Solution</h3>
<p>Firstly, ASP.NET MVC doesn’t have HTML helpers to generate the “[something].Index” pattern which is major problem since it means we can’t use validation and custom editors. We can fix that by utilizing some ASP.NET templating fu. What we are going to do is move the Movie editor to a its own partial view (MovieEntryEditor.cshtml):</p>
<pre class="brush: xml; title: ; notranslate">@model CollectionEditing.Models.Movie

&lt;li style=&quot;padding-bottom:15px&quot;&gt;
    @using (Html.BeginCollectionItem(&quot;FavouriteMovies&quot;)) {
        &lt;img src=&quot;@Url.Content(&quot;~/Content/images/draggable-icon.png&quot;)&quot; style=&quot;cursor: move&quot; alt=&quot;&quot;/&gt;

        @Html.LabelFor(model =&gt; model.Title)
        @Html.EditorFor(model =&gt; model.Title)
        @Html.ValidationMessageFor(model =&gt; model.Title)

        @Html.LabelFor(model =&gt; model.Rating)
        @Html.EditorFor(model =&gt; model.Rating)
        @Html.ValidationMessageFor(model =&gt; model.Rating)

        &lt;a href=&quot;#&quot; onclick=&quot;$(this).parent().remove();&quot;&gt;Delete&lt;/a&gt;
    }
&lt;/li&gt;
</pre>
</p>
<p>And update our Edit view to use it:</p>
<p>
<pre class="brush: xml; title: ; notranslate">
&lt;ul id=&quot;movieEditor&quot; style=&quot;list-style-type: none&quot;&gt;
    @foreach (Movie movie in Model.FavouriteMovies) {
        Html.RenderPartial(&quot;MovieEntryEditor&quot;, movie);
    }
&lt;/ul&gt;
&lt;p&gt;&lt;a id=&quot;addAnother&quot; href=&quot;#&quot;&gt;Add another&lt;/a&gt;</pre>
</p>
<p>Notice two things – firstly the Movie partial edit view uses standard Html helpers and secondly there is a call to something custom called <em>Html.BeginCollectionItem. </em>You might even ask yourself: Wait a second. This won’t work, because the partial view will produce names such as “Title” instead of “FavouriteMovies[xxx].Title”, so let me show you the source code of <em>Html.BeginCollectionItem</em>:</p>
<pre class="brush: csharp; title: ; notranslate">public static IDisposable BeginCollectionItem&lt;TModel&gt;(this HtmlHelper&lt;TModel&gt; html,                                                       string collectionName)
{
    string itemIndex = Guid.NewGuid().ToString();
    string collectionItemName = String.Format(&quot;{0}[{1}]&quot;, collectionName, itemIndex);

    TagBuilder indexField = new TagBuilder(&quot;input&quot;);
    indexField.MergeAttributes(new Dictionary&lt;string, string&gt;() {
        { &quot;name&quot;, String.Format(&quot;{0}.Index&quot;, collectionName) },
        { &quot;value&quot;, itemIndex },
        { &quot;type&quot;, &quot;hidden&quot; },
        { &quot;autocomplete&quot;, &quot;off&quot; }
    });

    html.ViewContext.Writer.WriteLine(indexField.ToString(TagRenderMode.SelfClosing));
    return new CollectionItemNamePrefixScope(html.ViewData.TemplateInfo, collectionItemName);
}

private class CollectionItemNamePrefixScope : IDisposable
{
    private readonly TemplateInfo _templateInfo;
    private readonly string _previousPrefix;

    public CollectionItemNamePrefixScope(TemplateInfo templateInfo, string collectionItemName)
    {
        this._templateInfo = templateInfo;

        _previousPrefix = templateInfo.HtmlFieldPrefix;
        templateInfo.HtmlFieldPrefix = collectionItemName;
    }

    public void Dispose()
    {
        _templateInfo.HtmlFieldPrefix = _previousPrefix;
    }
}</pre>
</p>
<p>This helper does two things:</p>
<ul>
<li>Appends a hidden Index field to the output with a random GUID value (remember that using the .Index pattern an index can be any string)</li>
<li>Scopes the execution of the helper via an <em>IDisposable</em> and sets the template rendering context (html helperes and display/editor templates) to be “<em>FavouriteMovies[GUID].</em>”, so we end up with HTML like this:</li>
</ul>
<p>
<pre class="brush: xml; title: ; notranslate">&lt;input autocomplete=&quot;off&quot; name=&quot;FavouriteMovies.Index&quot; type=&quot;hidden&quot; value=&quot;6d85a95b-1dee-4175-bfae-73fad6a3763b&quot; /&gt;
&lt;label&gt;Title&lt;/label&gt;
&lt;input class=&quot;text-box single-line&quot; name=&quot;FavouriteMovies[6d85a95b-1dee-4175-bfae-73fad6a3763b].Title&quot; type=&quot;text&quot; value=&quot;Movie 1&quot; /&gt;
&lt;span class=&quot;field-validation-valid&quot;&gt;&lt;/span&gt;</pre>
</p>
<p>This solves the problem of using Html field templates and basically reusing ASP.NET facilities instead of having to write html by hand, but it leads me to the second quirk that we need to address.</p>
<p>Let me show you the second and final problem. Disable client side validation and delete the title of e.g. “Movie 2” and click submit. Validation will fail, because Title of a movie is a required field, but while we are shown the edit form again<strong> there are no validation messages</strong>:</p>
<p><a href="http://ivanz.com/wp-content/uploads/2011/06/image4.png" rel="shadowbox[sbpost-786];player=img;"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="image" src="http://ivanz.com/wp-content/uploads/2011/06/image_thumb4.png" border="0" alt="image" width="544" height="174" /></a></p>
<p>Why is that? It’s the same problem I mentioned earlier in this post. Each time we render the view we assign different names to the fields, which do not match the ones submitted and leads to a <em>ModelState </em>inconsistency. We have to figure out how to persist the name and more specifically the Index across requests. We have two options:</p>
<ol>
<li>Add a hidden CollectionIndex field and CollectionIndex property on the <em>Movie</em> object to persist the <em>FavouriteMovies.Index</em>. This however is intrusive and suboptimal.</li>
<li>Instead of polluting the <em>Movie</em> object with an extra property be smart and in our helper <em>Html.BeginCollectionItem</em> reapply/reuse the submitted <em>FavouriteMovies.Index</em> form values.</li>
</ol>
<p>Let’s replace in <em>Html.BeginCollectionItem</em> this line:</p>
<p>
<pre class="brush: csharp; title: ; notranslate">string itemIndex = Guid.New().ToString();</pre>
<p>with:</p>
<pre class="brush: csharp; title: ; notranslate">string itemIndex = GetCollectionItemIndex(collectionIndexFieldName);</pre>
</p>
<p>And here&#8217; is the code for GetCollectionItemIndex:</p>
<pre class="brush: csharp; title: ; notranslate">private static string GetCollectionItemIndex(string collectionIndexFieldName)
{
    Queue&lt;string&gt; previousIndices = (Queue&lt;string&gt;) HttpContext.Current.Items[collectionIndexFieldName];
    if (previousIndices == null) {
        HttpContext.Current.Items[collectionIndexFieldName] = previousIndices = new Queue&lt;string&gt;();

        string previousIndicesValues = HttpContext.Current.Request[collectionIndexFieldName];
        if (!String.IsNullOrWhiteSpace(previousIndicesValues)) {
            foreach (string index in previousIndicesValues.Split(','))
                previousIndices.Enqueue(index);
        }
    }

    return previousIndices.Count &gt; 0 ? previousIndices.Dequeue() : Guid.NewGuid().ToString();
}</pre>
</p>
<p>We get all submitted values for e.g. “<em>FavouriteMovie.Index</em>” put them in a queue, which we store for the duration of the request. Each time we render a collection item we dequeue its old index value and if none is available we generate a new one. That way we preserve the Index across requests and can have a consistent <em>ModelState</em> and see validation errors and messages:</p>
<p><a href="http://ivanz.com/wp-content/uploads/2011/06/image5.png" rel="shadowbox[sbpost-786];player=img;"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="image" src="http://ivanz.com/wp-content/uploads/2011/06/image_thumb5.png" border="0" alt="image" width="684" height="150" /></a></p>
<p>All that is left is to implement the “Add another” button functionality and we can do that easily by appending a new row to the movie editor, which we can fetch using Ajax and use our existing MovieEntryEditor.cshtml partial view like that:</p>
<p>
<pre class="brush: csharp; title: ; notranslate">public ActionResult MovieEntryRow()
{
    return PartialView(&quot;MovieEntryEditor&quot;);
}</pre>
</p>
<p>And then add the follwing &#8220;Add Another&#8221; click handler:</p>
<p>
<pre class="brush: jscript; title: ; notranslate">$(&quot;#addAnother&quot;).click(function () {
    $.get('/User/MovieEntryRow', function (template) {
        $(&quot;#movieEditor&quot;).append(template);
    });
});</pre>
<p>Done.</p>
<h3>Conclusion</h3>
<p>While not immediately obvious editing variable length reorderable collections with standard ASP.NET MVC is possible and what I like about this approach is that:</p>
<ul>
<li>We can keep using traditional ASP.NET html helpers, editor and display templates (Html.EditorFor, etc.) with in our collection editing</li>
<li>We can make use of the ASP.NET MVC model validation client and server side</li>
</ul>
<p>What I don’t like that much however is:</p>
<ul>
<li>That we have to use an AJAX request to append a new row to the editor.</li>
<li>That we need to use the name of the collection in the movie editor partial view, but otherwise when doing the standalone AJAX get request the name context won’t be properly set for the partial template fields.</li>
</ul>
<p>I would love to hear your thoughts. The sample source code is available on my <a href="http://github.com/ivanz/ASP.NET-MVC-Collection-Editing" target="_blank">GitHub</a></p>
<p>Next: <strong><a href="http://ivanz.com/2011/06/20/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-2/">Part 2 and how to avoid having an AJAX request with the use of jQuery Templates</a></strong></p>
 <img src="http://ivanz.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=786" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
		<item>
		<title>Java BDD with JBehave and Watij in Eclipse with JUnit</title>
		<link>http://ivanz.com/2011/05/25/java-bdd-with-jbehave-and-watij-in-eclipse-with-junit/</link>
		<comments>http://ivanz.com/2011/05/25/java-bdd-with-jbehave-and-watij-in-eclipse-with-junit/#comments</comments>
		<pubDate>Wed, 25 May 2011 17:29:42 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[BDD]]></category>
		<category><![CDATA[HowTo]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://ivanz.com/?p=762</guid>
		<description><![CDATA[<a href="http://ivanz.com/2011/05/25/java-bdd-with-jbehave-and-watij-in-eclipse-with-junit/" title="Java BDD with JBehave and Watij in Eclipse with JUnit"></a>The purpose of this post is to explain how to write BDD acceptance tests in Java using the gherkin syntax, run those with JUnit and implement them using Web Browser automation. Before I begin let me assure you that I &#8230;<p class="read-more"><a href="http://ivanz.com/2011/05/25/java-bdd-with-jbehave-and-watij-in-eclipse-with-junit/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://ivanz.com/2011/05/25/java-bdd-with-jbehave-and-watij-in-eclipse-with-junit/" title="Java BDD with JBehave and Watij in Eclipse with JUnit"></a><p>The purpose of this post is to explain how to write BDD acceptance tests in Java using the gherkin syntax, run those with JUnit and implement them using Web Browser automation.</p>
<p>Before I begin let me assure you that I haven&#8217;t left the .NET church for the Java one and while I really don&#8217;t enjoy writing in Java and using Eclipse sometimes a man has to do what a man has to do.</p>
<p>So yeah I spend an afternoon trying to figure out the state of BDD (Behavior Driven Development) tools for Java and it&#8217;s pretty poor so far. If you want to write gherkin syntax based behavioral specifications, which are executable inside Eclipse as JUnit tests you are stuck only with <a href="http://jbehave.org/">JBehave</a>. JBehave however is a monster with poor documentation, not so easily discoverable fluent API and little to none third party documentation content on forums and sites. BTW don&#8217;t get fooled like me &#8211; insetad of getting the core package you want to get the Web package because the latter has all the .jar dependencies bundled unlike the first one. Enough bashing, lets get down to business.</p>
<p>Let&#8217;s say we have the following &#8220;Search&#8221; story and a more specific scenario &#8211; &#8220;display an error dialog if I don&#8217;t fill in the search form&#8221;:</p>
<pre class="brush: plain; title: ; notranslate">Narrative: I should be able to search

Scenario: I should see an error if I try to search without filling in the search form fields.

When I open 'http://mysite.com'
When I click on the 'Search' button
Then I should see an error</pre>
<p>First thing you will notice is that JBehave doesn&#8217;t support the &#8220;And&#8221; keyword so we can&#8217;t wring &#8220;When I open &#8230; AND I click on the Seach button&#8221;.</p>
<p>Similar to other gherkin/cucumber based frameworks JBehave allows us to implement each step of the scenario as a method in a class, which optionally takes parameters mapped to words from the scenario. The above one can be stubbed like bellow. Also not that if properly configured you can make JBehave junit runner spit out the stubs for you to copy paste in your code (more about that later):</p>
<pre class="brush: java; title: ; notranslate">
public class Search
{
	@When(&quot;I open '$page'&quot;)
	public void whenIOpen(String page)
	{
		// TODO
	}

	@When(&quot;I click on the '$buttonText' button&quot;)
	public void whenIClickOnTheButton(String buttonText)
	{
		// TODO
	}

	@Then(&quot;I should see an error&quot;)
	public void thenIShouldSeeAnError(){
		// TODO
	}
}</pre>
<p>To implement the browser automation in Java there exist a Java variant of the Ruby watir library (and the .NET Watin library) called &#8230; surprise&#8230; watiJ. It&#8217;s available <a href="http://watij.com/">here</a>. Major pitfall with it though is that it actually embeds the IE COM component and mozilla&#8217;s ghecko engine instead launching the real IE/Firefox (like the above mentioned framework do) and it only supports IE6 and I saw some C++ runtime problems with the ghecko engine. Nevertheless to give you a feel of how the above tests can be implemented:</p>
<pre class="brush: java; title: ; notranslate">
public class Search extends StoryBase {

	@When(&quot;I open '$page'&quot;)
	public void whenIOpen(String page)
	{
		WebBrowser.open(page).pauseUntilReady();
	}

	@When(&quot;I click on the '$buttonText' button&quot;)
	public void whenIClickOnTheButton(String buttonText)
	{
		Tag button = WebBrowser.find.button().with.name(&quot;search&quot;);
		assertNotNull(button);
		button.click().pauseUntilReady();
	}

	@Then(&quot;I should see an error&quot;)
	public void thenIShouldSeeAnError(){
		Tag errorDialogTitleDiv = WebBrowser.find.span().with.className(&quot;dijitDialogTitle&quot;);
		assertNotNull(errorDialogTitleDiv);
		assertEquals(&quot;Error&quot;, errorDialogTitleDiv.get.innerHTML());
	}
}</pre>
<p>Now, how about running them? A few things before that:</p>
<ul>
<li>JBehave expects you to save stories as .story files in your source code tree</li>
<li>JBehave expects you to implement and configure problematically a <em>JUnitStory </em>for each story, so that it&#8217;s runnable through JUnit.</li>
<li>It will take your JUnitStory subclass implementation &#8211; for example &#8220;<em>HelloWorldStory extends JUnitStory&#8221; </em>and look for the plain text file <em>hello_world_story.story</em></li>
</ul>
<p>To save myself from having to configure each story  I present you my <em>StoryBase </em>base class, which:</p>
<ul>
<li>Initializes WatiJ and exposes it to subclasses</li>
<li>Configures JBehave to look for the .story files in the same directory as the class.</li>
<li>Configures JBehave/JUnit to look for the steps test methods of a story scenario in the subclass.</li>
<li>Configures JBehave to print out detailed information in the Console whilst running (such as the method stubs if any are missing)</li>
<li>Configures JBehave to spit out HTML report in <em>myproject/target/jbehave-report/</em></li>
</ul>
<p>Here it is:</p>
<pre class="brush: java; title: ; notranslate">
public abstract class StoryBase extends JUnitStory {
    protected final static WebSpec WebBrowser = new WebSpec().ie();

    @Override
    public Configuration configuration() {
        return new MostUsefulConfiguration()
            .useStoryLoader(new LoadFromClasspath(this.getClass().getClassLoader()))
    	    .useStoryReporterBuilder(
    	    		new StoryReporterBuilder()
    	    			.withDefaultFormats()
    	    			.withFormats(Format.HTML, Format.CONSOLE)
    	    			.withRelativeDirectory(&quot;jbehave-report&quot;)
			);
    }

    @Override
    public List candidateSteps() {
        return new InstanceStepsFactory(configuration(), this).createCandidateSteps();
    }
}
</pre>
<p>Then all that&#8217;s left is to make the Search class extend the StoryBase class and it is now runnable in JUnit inside and outside Eclipse.</p>
<pre class="brush: java; title: ; notranslate">public class Search extends StoryBase {
}</pre>
<p><a href="http://ivanz.com/wp-content/uploads/2011/05/Untitled.png" rel="shadowbox[sbpost-762];player=img;"><img class="aligncenter size-full wp-image-764" title="Project Tree" src="http://ivanz.com/wp-content/uploads/2011/05/Untitled.png" alt="" width="178" height="108" /></a><br />
<a href="http://ivanz.com/wp-content/uploads/2011/05/junit.png" rel="shadowbox[sbpost-762];player=img;"><img class="aligncenter size-full wp-image-763" title="junit" src="http://ivanz.com/wp-content/uploads/2011/05/junit.png" alt="" width="649" height="85" /></a></p>
<p>&nbsp;</p>
 <img src="http://ivanz.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=762" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2011/05/25/java-bdd-with-jbehave-and-watij-in-eclipse-with-junit/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Triply: Day 11 Summary</title>
		<link>http://ivanz.com/2011/05/12/triply-day-11-summary/</link>
		<comments>http://ivanz.com/2011/05/12/triply-day-11-summary/#comments</comments>
		<pubDate>Thu, 12 May 2011 20:45:25 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Diary]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Start-Up]]></category>
		<category><![CDATA[Triply]]></category>

		<guid isPermaLink="false">http://ivanz.com/?p=760</guid>
		<description><![CDATA[<a href="http://ivanz.com/2011/05/12/triply-day-11-summary/" title="Triply: Day 11 Summary"></a>11 days ago I posted the launch notice for Triply. The only other place where I publicized it was on the Foursquare Apps list here. It was very surprising for me that given no &#8220;advertisement&#8221;, no web design and very little features &#8230;<p class="read-more"><a href="http://ivanz.com/2011/05/12/triply-day-11-summary/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://ivanz.com/2011/05/12/triply-day-11-summary/" title="Triply: Day 11 Summary"></a><p>11 days ago I <a title="Introducing Triply for Foursquare" href="http://ivanz.com/2011/05/02/introducing-triply-for-foursquare/">posted the launch notice</a> for <a href="http://triply.net">Triply</a>. The only other place where I publicized it was on the Foursquare Apps list <a href="https://foursquare.com/app/triply">here</a>. It was very surprising for me that given no &#8220;advertisement&#8221;, no web design and very little features it managed for 11 days to score:</p>
<ul>
<li>103 user accounts &#8211; 83 Foursquare and 22 Facebook</li>
<li>2226 actions performed around the site</li>
<li>651 visits</li>
<li>432 visitors</li>
<li>10 Twitter followers</li>
<li>14 Facebook page fans</li>
<li>2 Feature requests in UserVoice (completed)</li>
</ul>
<p>I used real time analytics (<a href="http://woopra.com">Woopra</a>) to monitor the users navigation flow (not that there are many pages to navigate around) and that helped me to optimize the experience, especially in terms of login flow. For example instead of asking the user to sign in with Foursquare or Facebook to share a trip I redesigned it to show the actual page and only prompt for login when the user needs to import Checkins. As they say a picture is worth a thousand words, but the actual thing is priceless.</p>
<p>Other new features since launch are:</p>
<ul>
<li>Facebook Places Checkins support</li>
<li>Browse trips interface where a user can browser trips, days out and experiences by City, Country and latest</li>
<li>Allow trips to be downloaded as a .GPX file which users can open with Google Earth and Garmin sat navs. Adding support for other geo formats for other satnavs won&#8217;t be hard either.</li>
<li>A lot of polish and fixes in the backend. Thanks god for <a href="http://code.google.com/p/elmah/">ELMAH</a>, which helped me log all problems around the site.</li>
</ul>
<p>What&#8217;s next?</p>
<p>I am on a cross road at the moment as I need:</p>
<ol>
<li>A web design (well overdue)</li>
<li>Someone to bounce ideas off and vice-versa (co-founder?) in which direction to take Triply as I think there are many directions Triply can go. For example I can make it the bit.ly for sharing trips/days out, etc or I can make it a trip diary type of thing by pulling and displaying photos of the trip from Flickr (using EXIF location data and search), etc. All fun ideas.</li>
</ol>
<p>But how do both of those fit together? Doesn&#8217;t the design depend on the future features and vice-versa?</p>
 <img src="http://ivanz.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=760" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2011/05/12/triply-day-11-summary/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Client-Side XSLT Transformations with JavaScript</title>
		<link>http://ivanz.com/2011/05/12/client-side-xslt-transformations-with-javascript/</link>
		<comments>http://ivanz.com/2011/05/12/client-side-xslt-transformations-with-javascript/#comments</comments>
		<pubDate>Thu, 12 May 2011 20:10:35 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Dojo]]></category>
		<category><![CDATA[HowTo]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://ivanz.com/?p=758</guid>
		<description><![CDATA[<a href="http://ivanz.com/2011/05/12/client-side-xslt-transformations-with-javascript/" title="Client-Side XSLT Transformations with JavaScript"></a>I bet you haven&#8217;t ever thought of doing XSLT transformations inside the Web Browser on the client-side, but anyway it&#8217;s absolutely possible (cross-browser) and it performs pretty well as well, which shouldn&#8217;t be a big surprise since the browser is &#8230;<p class="read-more"><a href="http://ivanz.com/2011/05/12/client-side-xslt-transformations-with-javascript/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://ivanz.com/2011/05/12/client-side-xslt-transformations-with-javascript/" title="Client-Side XSLT Transformations with JavaScript"></a><p>I bet you haven&#8217;t ever thought of doing XSLT transformations inside the Web Browser on the client-side, but anyway it&#8217;s absolutely possible (cross-browser) and it performs pretty well as well, which shouldn&#8217;t be a big surprise since the browser is optimized to work with markup.</p>
<p>Real-life practical applications of this however I haven&#8217;t thought of yet, but possibly:</p>
<ol>
<li>Use XSLT to consume old XML-based web services and convert the XML into JSON on the client side on the fly. Come on, I know you want to! Why do it properly when you can do it in JavaScript?</li>
<li>Create a JavaScript-only  CMS that loads Word documents directly and uses XSLT to display HTML (.docx is zipped xml). Again, why do it properly when you can do it in JavaScript?</li>
<li>For fun and zero profit!</li>
</ol>
<p>Here is the XSLT transformer JavaScript class and sample. The class uses the Dojo JavaScript framework, but only for the browser checks and AJAX requests, so you can easily replace those with JQuery if you wish. Take it under the MIT/X11 license. There is also a <a href="http://ivanz.com/files/demos/js-xslt/demo.html">useless demo here</a>.</p>
<p><em>Sample</em>:</p>
<pre class="brush: jscript; title: ; notranslate">
// to transform
var xslTransform = new XslTransform(&quot;/path/to/sample.xsl&quot;);
var outputText = xslTransform.transform(&quot;/path/to/sample.xml&quot;);
</pre>
<p><em>XslTransform.js</em>:</p>
<pre class="brush: jscript; title: ; notranslate">
dojo.provide(&quot;XslTransform&quot;);

dojo.declare(&quot;XslTransform&quot;, [],
{
	_xslDoc : null,
	_xslPath : null,

	constructor : function(xslPath) {
		this._xslPath = xslPath;
	},

	transform : function(xmlPath) {
		if (this._xslDoc === null)
			this._xslDoc = this._loadXML(this._xslPath);

		var result = null;
		var xmlDoc = this._loadXML(xmlPath);

		if (dojo.isIE) {
			result = xmlDoc.transformNode(this._xslDoc);
		} else if(typeof XSLTProcessor !== undefined) {
			xsltProcessor = new XSLTProcessor();
	  		xsltProcessor.importStylesheet(this._xslDoc);

	  		var ownerDocument = document.implementation.createDocument(&quot;&quot;, &quot;&quot;, null);
	  		result = xsltProcessor.transformToFragment(xmlDoc, ownerDocument);
		} else {
			alert(&quot;Your browser doesn't support XSLT!&quot;);
		}

		return result;

	},

	createXMLDocument : function(xmlText) {
		var xmlDoc = null;

		if (dojo.isIE) {
			xmlDoc = new ActiveXObject(&quot;Microsoft.XMLDOM&quot;);
			xmlDoc.async = false;
			xmlDoc.loadXML(xmlText);
		} else if (window.DOMParser) {
			parser = new DOMParser();
			xmlDoc = parser.parseFromString(xmlText, &quot;text/xml&quot;);
		} else {
			alert(&quot;Your browser doesn't suppoprt XML parsing!&quot;);
		}

		return xmlDoc;
	},

	// Synchronously loads a remote xml file
	_loadXML : function(xmlPath) {
		var getResult = dojo.xhrGet({
			url : xmlPath,
			handleAs : &quot;xml&quot;,
			sync: true
		});

		var xml = null;
		// Returns immediately, because the GET is synchronous.
		var xmlData = getResult.then(function (response) {
			xml = response;
		});

		return xml;
	}
});
</pre>
 <img src="http://ivanz.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=758" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2011/05/12/client-side-xslt-transformations-with-javascript/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Logging JavaScript Errors with ELMAH in ASP.NET MVC</title>
		<link>http://ivanz.com/2011/05/08/logging-javascript-errors-with-elmah/</link>
		<comments>http://ivanz.com/2011/05/08/logging-javascript-errors-with-elmah/#comments</comments>
		<pubDate>Sun, 08 May 2011 19:27:14 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[HowTo]]></category>

		<guid isPermaLink="false">http://ivanz.com/?p=753</guid>
		<description><![CDATA[<a href="http://ivanz.com/2011/05/08/logging-javascript-errors-with-elmah/" title="Logging JavaScript Errors with ELMAH in ASP.NET MVC"></a>One final piece of information I wanted to add to my last blog post about setting up ELMAH for ASP.NET MVC is how to log Client Side/JavaScript errors with ELMAH. To do that we need to: 1. Because ELMAH works &#8230;<p class="read-more"><a href="http://ivanz.com/2011/05/08/logging-javascript-errors-with-elmah/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://ivanz.com/2011/05/08/logging-javascript-errors-with-elmah/" title="Logging JavaScript Errors with ELMAH in ASP.NET MVC"></a><p>One final piece of information I wanted to add to <a title="ASP.NET MVC Magical Error Logging with ELMAH" href="http://ivanz.com/2011/05/08/asp-net-mvc-magical-error-logging-with-elmah/">my last blog post about setting up ELMAH for ASP.NET MVC</a> is how to log Client Side/JavaScript errors with <a href="http://code.google.com/p/elmah/">ELMAH</a>.</p>
<p>To do that we need to:</p>
<p>1. Because ELMAH works with exceptions we will need to define a <em>JavaScriptErrorException </em>to represent our client side errors in the logs:</p>
<pre class="brush: csharp; title: ; notranslate">using System;

namespace Triply.Extensions
{
	[Serializable]
	public class JavaScriptErrorException : Exception
	{
		public JavaScriptErrorException (string message) : base(message)
		{
		}
	}
}</pre>
<p>2. Define a Controller Action to be invoked by the client side that takes in an error message:</p>
<pre class="brush: csharp; title: ; notranslate">using System;
using System.Web.Mvc;
using Elmah;
using Triply.Extensions;

namespace Triply.Controllers
{
	public class HomeController : Controller
	{
		[HttpPost]
		public void LogJavaScriptError(string message)
		{
			ErrorSignal.FromCurrentContext().Raise(new JavaScriptErrorException(message));
		}
	}
}</pre>
<p>3. Use an AJAX post with a message to log the error</p>
<pre class="brush: jscript; title: ; notranslate">
function logError(details) {
    $.post(&quot;/Home/LogJavaScriptError&quot;, { message: details });
}
</pre>
<p>Done!</p>
 <img src="http://ivanz.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=753" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2011/05/08/logging-javascript-errors-with-elmah/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

