<?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; .NET</title>
	<atom:link href="http://ivanz.com/tag/dotnet/feed/" rel="self" type="application/rss+xml" />
	<link>http://ivanz.com</link>
	<description></description>
	<lastBuildDate>Sun, 22 Apr 2012 18:15:27 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<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>29</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>4</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC Magical Error Logging with ELMAH</title>
		<link>http://ivanz.com/2011/05/08/asp-net-mvc-magical-error-logging-with-elmah/</link>
		<comments>http://ivanz.com/2011/05/08/asp-net-mvc-magical-error-logging-with-elmah/#comments</comments>
		<pubDate>Sun, 08 May 2011 19:09:05 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[HowTo]]></category>

		<guid isPermaLink="false">http://ivanz.com/?p=749</guid>
		<description><![CDATA[<a href="http://ivanz.com/2011/05/08/asp-net-mvc-magical-error-logging-with-elmah/" title="ASP.NET MVC Magical Error Logging with ELMAH"></a>If you aren&#8217;t using ELMAH (Error Logging Modules and Handlers) you should be - http://code.google.com/p/elmah/ It&#8217;s the best thing since sliced bread for logging ASP.NET errors with practically zero effort. It basically plugs into the ASP.NET pipeline and logs all unhandled exceptions thrown and &#8230;<p class="read-more"><a href="http://ivanz.com/2011/05/08/asp-net-mvc-magical-error-logging-with-elmah/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://ivanz.com/2011/05/08/asp-net-mvc-magical-error-logging-with-elmah/" title="ASP.NET MVC Magical Error Logging with ELMAH"></a><p>If you aren&#8217;t using ELMAH (Error Logging Modules and Handlers) you should be - <a href="http://code.google.com/p/elmah/">http://code.google.com/p/elmah/</a> It&#8217;s the best thing since sliced bread for logging ASP.NET errors with practically zero effort. It basically plugs into the ASP.NET pipeline and logs all unhandled exceptions thrown and HTTP error codes together with all sorts of other useful information such as request url, stacktrace, current user username, cookies and more. You can say it makes a snapshot of the Yellow Screen of Death with extra information. It then gives you a simple web access to the recent errors logged (by default at http//mysite.com/elmah.axd), exposing a RSS feed as well. It&#8217;s fully configurable (error filters, multiple backend log storage systems support, etc) and also can be set up to send emails on error.</p>
<p>Some screenshots:</p>
<div class="wp-caption aligncenter" style="width: 310px"><a href="http://ivanz.com/wp-content/uploads/2011/05/elmah-log-1.png" rel="shadowbox[sbpost-749];player=img;"><img title="elmah-log-1" src="http://ivanz.com/wp-content/uploads/2011/05/elmah-log-1-300x43.png" alt="" width="300" height="43" /></a><p class="wp-caption-text">List of Errors using the Web Interface</p></div>
<div class="wp-caption aligncenter" style="width: 310px"><a href="http://ivanz.com/wp-content/uploads/2011/05/elmah-log-2.png" rel="shadowbox[sbpost-749];player=img;"><img title="elmah-log-2" src="http://ivanz.com/wp-content/uploads/2011/05/elmah-log-2-300x186.png" alt="" width="300" height="186" /></a><p class="wp-caption-text">Error Details in the web interface</p></div>
<p><a href="http://ivanz.com/wp-content/uploads/2011/05/elmah-log-1.png" rel="shadowbox[sbpost-749];player=img;"></a></p>
<p>You can pull ELMAH through nuget via the &#8220;Elmah&#8221; package., which will download it and add a reference. The steps to get it all set up for ASP.NET MVC are as follows.</p>
<p>1. Register Elmah configuration sections in the <em>Web.config</em></p>
<pre class="brush: xml; title: ; notranslate">    &lt;sectionGroup name=&quot;elmah&quot;&gt;
      &lt;section name=&quot;security&quot; requirePermission=&quot;false&quot; type=&quot;Elmah.SecuritySectionHandler, Elmah&quot; /&gt;
      &lt;section name=&quot;errorLog&quot; requirePermission=&quot;false&quot; type=&quot;Elmah.ErrorLogSectionHandler, Elmah&quot; /&gt;
      &lt;section name=&quot;errorMail&quot; requirePermission=&quot;false&quot; type=&quot;Elmah.ErrorMailSectionHandler, Elmah&quot; /&gt;
      &lt;section name=&quot;errorFilter&quot; requirePermission=&quot;false&quot; type=&quot;Elmah.ErrorFilterSectionHandler, Elmah&quot; /&gt;
    &lt;/sectionGroup&gt;</pre>
<p>2. Add the root level ELMAH section in <em>Web.config</em> to tell it where to store the logs and how. Easiest to set up is to have a directory where it stores xml file for each error, <strong>but make sure the IIS process/AppPool has write access to that directory!</strong> Also I have added a filter to ignore all HTTP 404 errors. Note that this filter won&#8217;t work for ASP.NET MVC and I will come back to that later.</p>
<pre class="brush: xml; title: ; notranslate">&lt;elmah&gt;
    &lt;security allowRemoteAccess=&quot;1&quot; /&gt;
    &lt;errorLog type=&quot;Elmah.XmlFileErrorLog, Elmah&quot; logPath=&quot;~/App_Data/ElmahLogs&quot; /&gt;
    &lt;errorFilter&gt;
      &lt;test&gt;
        &lt;equal binding=&quot;HttpStatusCode&quot; value=&quot;404&quot; type=&quot;Int32&quot; /&gt;
      &lt;/test&gt;
    &lt;/errorFilter&gt;
  &lt;/elmah&gt;</pre>
<p>3. Register ELMAH with the ASP.NET pipeline <strong>both</strong> in the <strong>system.web </strong>section (when running locally) and the  <strong>system.webServer</strong> section when deployed to IIS. Just copy paste the below snippet in both sections. Notice how the default configuration says that ELMAH will be available at mysite.com/elmah.axd . You can change that if you want (in both places!)</p>
<pre class="brush: xml; title: ; notranslate">    &lt;httpModules&gt;
      &lt;add name=&quot;ErrorLog&quot; type=&quot;Elmah.ErrorLogModule, Elmah&quot; /&gt;
    &lt;/httpModules&gt;
    &lt;httpHandlers&gt;
      &lt;add verb=&quot;POST,GET,HEAD&quot; path=&quot;elmah.axd&quot; type=&quot;Elmah.ErrorLogPageFactory, Elmah&quot; /&gt;
    &lt;/httpHandlers&gt;</pre>
<p>You are done and elmah will be available at http://mysite.com/elmah.axd , but it won&#8217;t work quite right with ASP.NET MVC, because of the way errors are handled there, so there are those additional things that need to be set up:</p>
<p>4. Log exceptions before ASP.NET MVC swallows them if using customErrors or some other code handles and swallows the error. To do this I&#8217;ve implemented the below exception filter that logs all handled exceptions. It&#8217;s a good example also of how to programatically log errors with ELMAH:</p>
<pre class="brush: csharp; title: ; notranslate">using System;
using System.Web.Mvc;
using Elmah;

namespace Triply.Extensions
{
	public class ElmahHandledErrorLoggerFilter : IExceptionFilter
	{
		public void OnException (ExceptionContext context)
		{
			// Long only handled exceptions, because all other will be caught by ELMAH anyway.
			if (context.ExceptionHandled)
				ErrorSignal.FromCurrentContext().Raise(context.Exception);
		}
	}
}</pre>
<p>To register it add it in <em>Global.asax.cs</em>. The ordering is important &#8211; <strong>add it before the HandleErrorAttribute is registered</strong>.</p>
<pre class="brush: csharp; title: ; notranslate">public static void RegisterGlobalFilters (GlobalFilterCollection filters)
{
	filters.Add(new ElmahHandledErrorLoggerFilter());
	filters.Add(new HandleErrorAttribute());
}</pre>
<p>5. One final note regarding filtering out HTTP 404 errors. In ASP.NET MVC they are raised as exceptions so if you want to ignore them unfortunately you can&#8217;t do that declaratively in the Web.config. Instead you have to add the following elmah hooks to your <em>Global.asax.cs</em> to do it programatically:</p>
<pre class="brush: csharp; title: ; notranslate">		// ELMAH Filtering
		protected void ErrorLog_Filtering (object sender, ExceptionFilterEventArgs e)
		{
			FilterError404(e);
		}

		protected void ErrorMail_Filtering (object sender, ExceptionFilterEventArgs e)
		{
			FilterError404(e);
		}

		// Dismiss 404 errors for ELMAH
		private void FilterError404 (ExceptionFilterEventArgs e)
		{
			if (e.Exception.GetBaseException() is HttpException) {
				HttpException ex = (HttpException)e.Exception.GetBaseException();
				if (ex.GetHttpCode() == 404)
					e.Dismiss();
			}
		}</pre>
<p>That&#8217;s it. Now you get super cool logging (and remember &#8211; RSS feed!)</p>
<p><a href="http://ivanz.com/wp-content/uploads/2011/05/elmah-log-1.png" rel="shadowbox[sbpost-749];player=img;"><br />
</a></p>
 <img src="http://ivanz.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=749" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2011/05/08/asp-net-mvc-magical-error-logging-with-elmah/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Storing Date and Time in UTC and the definition &#8220;Today&#8221;</title>
		<link>http://ivanz.com/2011/04/04/storing-date-and-time-in-utc-and-the-definition-today/</link>
		<comments>http://ivanz.com/2011/04/04/storing-date-and-time-in-utc-and-the-definition-today/#comments</comments>
		<pubDate>Mon, 04 Apr 2011 22:25:25 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[HowTo]]></category>

		<guid isPermaLink="false">http://ivanz.com/?p=732</guid>
		<description><![CDATA[<a href="http://ivanz.com/2011/04/04/storing-date-and-time-in-utc-and-the-definition-today/" title="Storing Date and Time in UTC and the definition &quot;Today&quot;"></a>Storing date and times in UTC on the server side is all nice and dandy, however there are a few gotchas, one of which the definition of &#8220;Today&#8221; when you a dealing with time zones. Say we are dealing with &#8230;<p class="read-more"><a href="http://ivanz.com/2011/04/04/storing-date-and-time-in-utc-and-the-definition-today/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://ivanz.com/2011/04/04/storing-date-and-time-in-utc-and-the-definition-today/" title="Storing Date and Time in UTC and the definition &quot;Today&quot;"></a><p>Storing date and times in UTC on the server side is all nice and dandy, however there are a few gotchas, one of which the definition of &#8220;Today&#8221; when you a dealing with time zones.</p>
<p>Say we are dealing with a system where a user can keep a history/log of all the food that he eats along with the date and time of when that happened. Current system times are:</p>
<blockquote><p>Current User Time (UTC+2): 4 April 01:45<br />
Current Server time (UTC): 3 April 23:45</p></blockquote>
<p>and we have two log entries:</p>
<blockquote><p>Log Entry User local time (UTC+2): 3 April 19:30<br />
Log Entry Server UTC time: 3 April 17:30</p></blockquote>
<blockquote><p>Log Entry User local time (UTC+2): 4 April 01:30<br />
Log Entry Server UTC time: 3 April 23:30</p></blockquote>
<p>If a user wants to see all the log entries for &#8220;Today&#8221; his perspective for today is 4 April, but if we use the current UTC date on the server (3 April) to do the query we are going to end up with two results, but only one of them (the second) is for the 4 April. This makes perfect sense on the server side, because from the server end perspective both of those log entries were logged on the 3rd, but that&#8217;s not the case with the user.</p>
<p>To solve this we need to calculate the start of user today day and end of user today day and use it as a range to query the log history.</p>
<p>The steps are more or less:</p>
<p>1. Get the current server time and convert it to user time.</p>
<p>2. &#8220;Rewind&#8221; that user time back to midnight (00:00)</p>
<p>3. Convert that to back UTC and you get the start of day for the user in server terms.</p>
<p>4. Add 23 hours, 59 minutes, 59 seconds to the above and you have the end of user day in server terms</p>
<p>5. Query for user_start_of_day &lt;= logentry.Date &lt;= user_end_of_day</p>
<p>A worked example for the above dates and times:</p>
<blockquote><p>Current Server time (UTC): 3 April 23:45</p></blockquote>
<p>1. Server time UtcNow is 3 April 23:45 and the user is in UTC+2, so the user local time is 4 April 01:45</p>
<p>2. This gives start of day for the user local time at 4 April 00:00</p>
<p>3. Which is 3 April 22:00 in server UTC time &#8211; the user_start_of_day</p>
<p>4. + 23:59:59 gives us 4 April 21:59:59 as the end of day</p>
<p>5. We query for log entries where the log UTC timestamp is between 3 April 22:00 and 4 April 21:59:59 , which will return only one result in the above case, which is correct.</p>
<p>Here is also a C# TimeZone class I have for each of my users in one of my toy projects:</p>
<pre class="brush: csharp; title: ; notranslate">public class TimeZone : Entity
{
    protected TimeZone ()
    {
    }

    public TimeZone (string name, TimeZoneInfo timeZone)
    {
        if (timeZone == null)
            throw new ArgumentNullException (&quot;timeZone&quot;, &quot;timeZone is null.&quot;);
        if (String.IsNullOrEmpty (name))
            throw new ArgumentException (&quot;name is null or empty.&quot;, &quot;name&quot;);

        Name = name;
        this.TimeZoneInfo = timeZone;
    }

    public virtual string Name { get; set; }
    public virtual TimeZoneInfo TimeZoneInfo { get; set; }

    public virtual DateTime StartOfToday {
        get {
            DateTime serverNow = DateTime.UtcNow;
            DateTime userNow = ToLocalTime(serverNow);
            return ToUniversalTime (userNow.Date);
        }
    }

    public virtual DateTime EndOfToday {
        get { return StartOfToday.Add (new TimeSpan (23, 59, 59)); }
    }

    public virtual DateTime ToLocalTime (DateTime utcTime)
    {
        return TimeZoneInfo.ConvertTimeFromUtc (utcTime, this.TimeZoneInfo);
    }

    public virtual DateTime ToUniversalTime (DateTime localTime)
    {
        if (localTime.Kind == DateTimeKind.Utc)
            return localTime;

        return TimeZoneInfo.ConvertTimeToUtc (localTime, this.TimeZoneInfo);
    }
}</pre>
<p>P.S: Some of you will spot a further implication of this and that is that we must always store the time as well as the date.</p>
 <img src="http://ivanz.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=732" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2011/04/04/storing-date-and-time-in-utc-and-the-definition-today/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>PicasaUploader 0.5: Upload videos</title>
		<link>http://ivanz.com/2010/06/05/picasauploader-0-5-upload-videos/</link>
		<comments>http://ivanz.com/2010/06/05/picasauploader-0-5-upload-videos/#comments</comments>
		<pubDate>Sat, 05 Jun 2010 16:19:20 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[PicasaWeb]]></category>

		<guid isPermaLink="false">http://ivanz.com/?p=720</guid>
		<description><![CDATA[<a href="http://ivanz.com/2010/06/05/picasauploader-0-5-upload-videos/" title="PicasaUploader 0.5: Upload videos"></a>I have released version 0.5 of PicasaUploader - the simple PicasaWeb uploader tool. Changes: Add support for uploading videos. Supported files are: .avi, .mpeg, .mpg, .wmv, .3gp, .asf, .mp4, .mov. However PicasaWeb can still reject any of those if it &#8230;<p class="read-more"><a href="http://ivanz.com/2010/06/05/picasauploader-0-5-upload-videos/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://ivanz.com/2010/06/05/picasauploader-0-5-upload-videos/" title="PicasaUploader 0.5: Upload videos"></a><p>I have released version 0.5 of <a href="http://ivanz.com/projects/picasauploader/">PicasaUploader </a>- the simple PicasaWeb uploader tool. Changes:</p>
<ul>
<li>Add support for uploading videos.
<ul>
<li>Supported files are: .avi, .mpeg, .mpg, .wmv, .3gp, .asf, .mp4, .mov. However PicasaWeb can still reject any of those if it doesn&#8217;t like it. Note also that videos won&#8217;t be playable in the album immediately because they have to be postprocessed by PicasaWeb.</li>
</ul>
</li>
<li>File size limits: 20MB for photo files and 100MB for video files.</li>
</ul>
<p>Get it <a href="http://ivanz.com/projects/picasauploader/">here</a>.</p>
<div id="attachment_719" class="wp-caption aligncenter" style="width: 310px"><a href="http://ivanz.com/wp-content/uploads/2009/04/video-upload1.png" rel="shadowbox[sbpost-720];player=img;"><img class="size-medium wp-image-719" title="Video Upload" src="http://ivanz.com/wp-content/uploads/2009/04/video-upload1-300x221.png" alt="Video Upload" width="300" height="221" /></a><p class="wp-caption-text">Video Upload</p></div>
 <img src="http://ivanz.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=720" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2010/06/05/picasauploader-0-5-upload-videos/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Three new featurelets for Fluent NHibernate</title>
		<link>http://ivanz.com/2009/12/13/three-new-featurelets-for-fluent-nhibernate/</link>
		<comments>http://ivanz.com/2009/12/13/three-new-featurelets-for-fluent-nhibernate/#comments</comments>
		<pubDate>Sun, 13 Dec 2009 17:58:21 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://ivanz.com/?p=702</guid>
		<description><![CDATA[<a href="http://ivanz.com/2009/12/13/three-new-featurelets-for-fluent-nhibernate/" title="Three new featurelets for Fluent NHibernate"></a>Lately I have been using Fluent NHibernate and NHibernate respectively for my ORM (Object-Relational Mapping) when working on my top secret pet project. Simply put &#8211; it&#8217;s great. Mapping is done using a fluent C# interface which makes use of &#8230;<p class="read-more"><a href="http://ivanz.com/2009/12/13/three-new-featurelets-for-fluent-nhibernate/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://ivanz.com/2009/12/13/three-new-featurelets-for-fluent-nhibernate/" title="Three new featurelets for Fluent NHibernate"></a><p>Lately I have been using <a href="http://fluentnhibernate.org/">Fluent NHibernate</a> and <a href="http://nhforge.org">NHibernate</a> respectively for my ORM (Object-Relational Mapping) when working on my top secret pet project. Simply put &#8211; it&#8217;s great. Mapping is done using a fluent C# interface which makes use of lambda expressions for referencing properties instead of strings (check my <a href="http://ivanz.com/2009/12/04/how-to-avoid-passing-property-names-as-strings-using-c-3-0-expression-trees/">previous post</a> for more info) so the domain model is <strong>safe to refactor</strong> because the mapping will be kept up-to-date too.</p>
<p>I spend some time hacking on Fluent NHibernate to add three little features I needed for my integration unit testing via Fluent NHibernate&#8217;s <em>PersistenceSpecification</em>. They all currently live in my GitHub(also used by Fluent NHibernate) fork <a href="http://github.com/ivanz/fluent-nhibernate">here</a> and have all been submitted upstream. <strong>UPDATE:</strong> The changes are as of now (21.12.2009) officially part of Fluent NHibernate. I can only hope you will find them useful as well.</p>
<h3>PersistenceSpecification: More Informational Error Reporting</h3>
<p>Particularly useful to troubleshoot failing mapping integration unit tests when a property check fails it will print both expected and actual types of the values. Also notice that chained properties (object.PropA.PropB) are now supported as well:</p>
<p style="padding-left: 30px;"><em>For property &#8216;Nutrition.Calories&#8217; expected &#8217;400&#8242; of type &#8216;System.Int32&#8242; but got &#8217;400&#8242; of type &#8216;System.Single&#8217;.</em></p>
<p>instead of:</p>
<p style="padding-left: 30px;"><em>Expected &#8217;400&#8242; but got &#8217;400&#8242; for Property &#8216;NutritionCalories&#8217;</em></p>
<h3>PersistenceSpecification: Entity Components Property Testing</h3>
<p>It is now possible to test entity component properties. For example given this domain model:</p>
<pre class="brush: csharp; title: ; notranslate">
public class Food
{
    public Food ()
    {
        Nutrition = new NutritionInfo ();
    }

    public virtual NutritionInfo Nutrition { get; protected set }
    public virtual int Id { get; set; }

}

public class NutritionInfo
{
    public virtual float? Fat { get; set; }
}
</pre>
<p>and this mapping:</p>
<pre class="brush: csharp; title: ; notranslate">
public class FoodMap : ClassMap&lt;Food&gt;
{
    public FoodMap ()
    {
        Id (food =&gt; food.Id)
            .GeneratedBy.Native ();

        Component&lt;NutritionInfo&gt; (food =&gt; food.Nutrition,
            mapping =&gt; {
                mapping.Map (nutrition =&gt; nutrition.Fat)
                    .Nullable ();
            }
        ).Access.BackingField ();
    }
}
</pre>
<p>One can now use this in unit tests:</p>
<pre class="brush: csharp; title: ; notranslate">
[TestMethod]
public void Food_Mapping ()
{
    new PersistenceSpecification&lt;Food&gt; (Session)
    .CheckProperty (food =&gt; food.Id, 1)
    .CheckProperty (food =&gt; food.Nutrition.Fat, 40f) // &lt;-- This one
    .VerifyTheMappings ();

}
</pre>
<p>Prior to my patch this wasn&#8217;t possible because Fluent Nhibernate <em>PersistenceSpecification</em> did not support chained properties and was trying to set a <em>Fat</em> property on the <em>food</em> object. Note that this is useful only for components and <span style="text-decoration: underline;">not</span> references. For the latter <em>.CheckReference (&#8230;) </em>should be used which will also commit the reference to the Database before doing anything else.</p>
<h3>PersistenceSpecification: IEqualityComparer for Individual Properties</h3>
<p>Given the setup from above it is now possible to set an IEqualityComparer per property, e.g.:</p>
<pre class="brush: csharp; title: ; notranslate">
[TestMethod]
public void Serving_Mapping ()
{

    new PersistenceSpecification&lt;Food&gt; (Session, new EqualityComparerForAllProperties ())
    .CheckProperty (food =&gt; food.Id, 1)
    .CheckProperty (food =&gt; food.Nutrition.Fat, 40f, FloatEqualityComparer.Instance)
    .VerifyTheMappings ();
}
</pre>
<p>If there is no comparer set for the property it will fall back to using the <em>EqualityComparerForAllProperties</em> and if that is not specified it will just use Object.Equals.</p>
 <img src="http://ivanz.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=702" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2009/12/13/three-new-featurelets-for-fluent-nhibernate/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>How to avoid passing property names as strings using C# 3.0 Expression Trees</title>
		<link>http://ivanz.com/2009/12/04/how-to-avoid-passing-property-names-as-strings-using-c-3-0-expression-trees/</link>
		<comments>http://ivanz.com/2009/12/04/how-to-avoid-passing-property-names-as-strings-using-c-3-0-expression-trees/#comments</comments>
		<pubDate>Fri, 04 Dec 2009 19:08:20 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://ivanz.com/?p=699</guid>
		<description><![CDATA[<a href="http://ivanz.com/2009/12/04/how-to-avoid-passing-property-names-as-strings-using-c-3-0-expression-trees/" title="How to avoid passing property names as strings using C# 3.0 Expression Trees"></a>Referencing property names via strings is evil. Consider this simplistic example: If at some point the property gets renamed the code will compile fine but a bug will be introduced as all those strings that contain the property name will &#8230;<p class="read-more"><a href="http://ivanz.com/2009/12/04/how-to-avoid-passing-property-names-as-strings-using-c-3-0-expression-trees/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://ivanz.com/2009/12/04/how-to-avoid-passing-property-names-as-strings-using-c-3-0-expression-trees/" title="How to avoid passing property names as strings using C# 3.0 Expression Trees"></a><p>Referencing property names via strings is evil. Consider this simplistic example:</p>
<pre class="brush: csharp; title: ; notranslate">
private int _myProperty;

public int MyProperty
{
    get { return _myProperty; }
    set {
        _myProperty = value;
        NotifyPropertyChanged (this, &quot;MyProperty&quot;)
    }
}

// Somewhere in a different project or file...
private void NotifyPropertyChanged (object sender, string propertyName)
{
    if (propertyName == &quot;MyProperty&quot;)
        Console.WriteLine (&quot;Property Changed&quot;);
}
</pre>
<p>If at some point the property gets renamed the code will compile fine but a bug will be introduced as all those strings that contain the property name will remain unchanged. Evil.</p>
<p>So I have been toying with NHibernate lately and yesterday I was writing some repositories. Let&#8217;s assume that theoretically they look like this:</p>
<pre class="brush: csharp; title: ; notranslate">
public class Repository &lt;TEntity&gt;
{
    public virtual TEntity FindById (object id)
    {
        ...
    }
}

public class UserRepository : Repository&lt;User&gt;
{
    public IList&lt;User&gt; FindByName (string name)
    {
        // query code
    }

    public IList&lt;User&gt; FindByEmail (string email)
    {
        // query code
    }
}
</pre>
<p>Both <em>FindByName </em>and <em>FindByEmail </em>in <em>UserRepository </em>will in theory contain the same queries but with different parameters. However I don&#8217;t really want to have to write individual queries so I considered a utility method:</p>
<pre class="brush: csharp; title: ; notranslate">
public class Repository &lt;TEntity&gt;
{
    public virtual TEntity FindById (object id)
    {
        ...
    }

    protected virtual IList&lt;TEntity&gt; FindByProperty (string propertyName, object value)
    {
        string columnName = NHibernateUtil.GetPropertyColumnName&lt;TEntity&gt; (propertyName);

        // Query here, e.g: &quot;SELECT .... WHERE .... columnName = value&quot; , etc.
    }
}

public class UserRepository : Repository&lt;User&gt;
{
    public IList&lt;User&gt; FindByName (string name)
    {
        return base.FindByProperty (&quot;Name&quot;, name);
    }

    public IList&lt;User&gt; FindByEmail (string email)
    {
        return base.FindByProperty (&quot;Email&quot;, email);
    }
}
</pre>
<p>Again this is very bad code and I hated the idea of it, so I sat down and started thinking. I remembered reading somewhere about C# 3.0 Expression Trees so I did some research. When using the special <em>Expression </em>type this seems to tell the compiler to create and expose an AST to us of e.g. a lambda function&#8217;s body, so if we pass a property reference expression we can parse the AST and extract the property name from there.</p>
<p>The theory in practice:</p>
<pre class="brush: csharp; title: ; notranslate">
public class UserRepository : Repository&lt;User&gt;
{
    public IList&lt;User&gt; FindByName (string name)
    {
        return base.FindByProperty (user =&gt; user.Name, name);
    }

    public IList&lt;User&gt; FindByEmail (string email)
    {
        return base.FindByProperty (user =&gt; user.Email, email);
    }
}

public class Repository &lt;TEntity&gt;
{
    public virtual TEntity FindById (object id)
    {
        ...
    }

    protected virtual IList&lt;TEntity&gt; FindByProperty (Expression&lt;Func&lt;TEntity, object&gt;&gt; propertyRefExpr,
                                                     object value)
    {
        string propertyName = GetPropertyName (propertyRefExpr);

        // Query code
    }

    private string GetPropertyName (Expression propertyRefExpr)
    {
        if (propertyRefExpr == null)
            throw new ArgumentNullException (&quot;propertyRefExpr&quot;, &quot;propertyRefExpr is null.&quot;);

        MemberExpression memberExpr = propertyRefExpr.Body as MemberExpression;
        if (memberExpr == null) {
            UnaryExpression unaryExpr = propertyRefExpr.Body as UnaryExpression;
            if (unaryExpr != null &amp;&amp; unaryExpr.NodeType == ExpressionType.Convert)
                memberExpr = unaryExpr.Operand as MemberExpression;
        }

        if (memberExpr != null &amp;&amp; memberExpr.Member.MemberType == MemberTypes.Property)
            return memberExpr.Member.Name;

        throw new ArgumentException (&quot;No property reference expression was found.&quot;,
                         &quot;propertyRefExpr&quot;);
    }
}
</pre>
<p>Also as a helper class:</p>
<pre class="brush: csharp; title: ; notranslate">
public static class PropertyUtil
{
    public static string GetPropertyName&lt;TObject&gt; (this TObject type,
                                                   Expression&lt;Func&lt;TObject, object&gt;&gt; propertyRefExpr)
    {
        return GetPropertyNameCore (propertyRefExpr.Body);
    }

    public static string GetName&lt;TObject&gt; (Expression&lt;Func&lt;TObject, object&gt;&gt; propertyRefExpr)
    {
        return GetPropertyNameCore (propertyRefExpr.Body);
    }

    private static string GetPropertyNameCore (Expression propertyRefExpr)
    {
        if (propertyRefExpr == null)
            throw new ArgumentNullException (&quot;propertyRefExpr&quot;, &quot;propertyRefExpr is null.&quot;);

        MemberExpression memberExpr = propertyRefExpr as MemberExpression;
        if (memberExpr == null) {
            UnaryExpression unaryExpr = propertyRefExpr as UnaryExpression;
            if (unaryExpr != null &amp;&amp; unaryExpr.NodeType == ExpressionType.Convert)
                memberExpr = unaryExpr.Operand as MemberExpression;
        }

        if (memberExpr != null &amp;&amp; memberExpr.Member.MemberType == MemberTypes.Property)
            return memberExpr.Member.Name;

        throw new ArgumentException (&quot;No property reference expression was found.&quot;,
                         &quot;propertyRefExpr&quot;);
    }
}
</pre>
<p>As you can see it contains two generic methods that operate either on types:</p>
<pre class="brush: csharp; title: ; notranslate">
string propertyName = PropertyUtil.GetName&lt;User&gt; (u =&gt; u.Email);
</pre>
<p>or instances:</p>
<pre class="brush: csharp; title: ; notranslate">
User user = GetUser();
string propertyName = user.GetPropertyName (u =&gt; u.Email);
</pre>
<p>Great, isn&#8217;t it? And safe to refactor.</p>
<p>Of course there is no such thing as a free lunch and the use of expression trees comes at the expense of some performance.</p>
<p>BTW is the font size of the code snippets sufficiently readable or is it too tiny?</p>
<p><strong>UPDATE:</strong> Added support for Convert expressions (implicit/explicit casting)</p>
 <img src="http://ivanz.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=699" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2009/12/04/how-to-avoid-passing-property-names-as-strings-using-c-3-0-expression-trees/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>HowTo Disable the Unsigned Security Warnings on Windows Mobile</title>
		<link>http://ivanz.com/2009/08/15/howto-disable-the-unsigned-security-warnings-on-windows-mobile/</link>
		<comments>http://ivanz.com/2009/08/15/howto-disable-the-unsigned-security-warnings-on-windows-mobile/#comments</comments>
		<pubDate>Sat, 15 Aug 2009 20:54:05 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[HowTo]]></category>
		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://i-nz.net/?p=674</guid>
		<description><![CDATA[<a href="http://ivanz.com/2009/08/15/howto-disable-the-unsigned-security-warnings-on-windows-mobile/" title="HowTo Disable the Unsigned Security Warnings on Windows Mobile"></a>The security warnings when deploying unsigned applications from Visual Studio to a real Windows Mobile device can get very annoying. Thankfully they can be disabled with a hack and here is how. Using the Remote Registry Editor supplied with Visual &#8230;<p class="read-more"><a href="http://ivanz.com/2009/08/15/howto-disable-the-unsigned-security-warnings-on-windows-mobile/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://ivanz.com/2009/08/15/howto-disable-the-unsigned-security-warnings-on-windows-mobile/" title="HowTo Disable the Unsigned Security Warnings on Windows Mobile"></a><p>The security warnings when deploying unsigned applications from Visual Studio to a real Windows Mobile device can get very annoying. Thankfully they can be disabled with a hack and here is how.</p>
<p>Using the Remote Registry Editor supplied with Visual Studio and with the Windows Mobile SDK installed change the following key value from 0 to 1 (and vise-versa to reset the change)</p>
<pre><code>HKEY_LOCAL_MACHINE\Security\Policies\Policies\0000101a = 1</code></pre>
<p>That&#8217;s it.</p>
 <img src="http://ivanz.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=674" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2009/08/15/howto-disable-the-unsigned-security-warnings-on-windows-mobile/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Visual Studio 2008 jQuery IntelliSense Fix</title>
		<link>http://ivanz.com/2009/07/01/visual-studio-2008-jquery-intellisense-fix/</link>
		<comments>http://ivanz.com/2009/07/01/visual-studio-2008-jquery-intellisense-fix/#comments</comments>
		<pubDate>Wed, 01 Jul 2009 21:25:16 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Bugs]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://i-nz.net/?p=592</guid>
		<description><![CDATA[<a href="http://ivanz.com/2009/07/01/visual-studio-2008-jquery-intellisense-fix/" title="Visual Studio 2008 jQuery IntelliSense Fix"></a>I am tinkering with ASP.NET MVC and jQuery and making my first baby steps in a whole new horrible world of web development. I found out that the JavaScript IntelliSense in Visual Studio 2008 is broken out of the box. &#8230;<p class="read-more"><a href="http://ivanz.com/2009/07/01/visual-studio-2008-jquery-intellisense-fix/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://ivanz.com/2009/07/01/visual-studio-2008-jquery-intellisense-fix/" title="Visual Studio 2008 jQuery IntelliSense Fix"></a><p>I am tinkering with ASP.NET MVC and jQuery and making my first baby steps in a whole new horrible world of web development. I found out that the JavaScript IntelliSense in Visual Studio 2008 is broken out of the box. The error is:</p>
<pre>Warning    2    Error updating JScript IntelliSense: jquery-1.3.2.js:
   Object doesn't support this property or method @ 2173:1</pre>
<p>The fix for Visual Studio 2008 SP1 by Microsoft can be found here:</p>
<p><a href="http://code.msdn.microsoft.com/KB958502">KB958502 &#8211; JScript Editor support for “-vsdoc.js” IntelliSense doc. files</a></p>
 <img src="http://ivanz.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=592" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2009/07/01/visual-studio-2008-jquery-intellisense-fix/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

