Twin Cities Code Camp 2012 – Day 1

This post will be a compilation of my notes from Twin Cities Code Camp 2012.

Understanding WebAPI in ASP.NET MVC 4 – Matt Milner – Rapson 56

What is web api?

  • API for HTTP Services – client and server components
  • WCF vs MVC – why do we need this api?
  • WCF – some people just want HTTP, REST services is complicated. Global error handling is almost impossible. Goal was to make WCF extremely flexible. Transport neutral just like SOAP. Because WCF was trying to cover ALL transports and protocols, HTTP became buried.

MVC was primarily built to pass back a View – typically HTML. JSON/JSONP were after thoughts. This is not a perfect model for RESTful services.

HTTP is a protocol in and of itself. Don’t need another protocol (e.g. SOAP). The protocol has been optimized over the years.

HTTP is widely accessible and MUCH easier to reach ALL devices.

Web API MVC Integration

  • MVC is for web applications
  • Web API is for web APIs
  • what they have in common is usually the model or domain

Cool new features: media type formatters for resource type handling. validation at the handler level which supports cancelation and pass-through instead of lowest level – the action. Better json support with the new System.Json library. Self-hosted testing built upon a partial wcf service stack. Support for OData URI queries. Simply return IQueryable. CONS: partial support for OData – only $page, $filter, and $sort – not $select. Doesn’t seem like the will be adding support for this. There is talk about adding built in support for Expression for DTO transformation on the server side.

There is also talk about combining the ServiceResolver configuration (configuration.ServiceResolver.SetResolver) to support both MVC and WebAPI in the same call. For example, right now you configure your MVC service resolving and a separate configuration for WebAPI service resolving. Simplification of this is on the table. Hopefully by the time the release comes around, we see a unified method.

TAKEAWAY MESSAGE: FORGET COMPLICATED SOAP PROTOCOL which is the standard for RIA Services and WCF. Simplify your api with REST. Forget about the mvc paradigm of method based access to your resources. You now access your resources via GET, POST, PUT, DELETE. You access a resource from a Controller. One controller per type of resource. Web API has content negotiation. It returns the data in the format that your request based on the Accept header. If I want JSON, I get JSON. You could expand upon this to return resources in whatever format you need; image, doc, resume, and more. The same for xml. Etc… Input validation is handled by the model binding mechanisms of MVC which builds a model state object.

Note: WebAPI is NOT a replacement for WCF. If you still need to support multiple endpoints in different protocols (for example pure TCP), then WCF is still the best option out there. If you want a simplified API that will be accessible for the widest audience, consider WebAPI.

NOTE TO SELF: check out $.validator.unobtrusive.revalidate(form, validationResult) – validationResult is the json object; { “Speaker”: “Speaker is required” } – where in this example Speaker is the name attribute of the form input element – this takes a json object and interprets it using jquery.validation unobtrusive. Is this a NEW method?

Async Today and Tomorrow – Joe Mayo – Rapson 54

Talk about the Async CTP. How we use async programming today and how we will use it in the future. The Async CTP hides the complexity of async programming. It leverages the TPL (Tasks Parallel Library).

Why do we need async for UI responsiveness? Ex. click on a button in a Windows Form. The program does some long running operation. The user doesn’t know what is happening until all of a sudden, the UI shows something. NOT A GOOD USER EXPERIENCE.

TPL at it’s core revolves around the Task class. It has a fluent api. Uses continuation methods (similar to callbacks).

  • Language Integration – Changes to C# and VB in .NET. Async – the await and async Context Keywords.
  • Every platform – Desktop, Web, and Device
  • leverage Opportunities – Clarity, lifetime, progress, UI, and exceptions

void functions – regular event handlers
functions that return typeof Task<T>– represents the ongoing operation – get exceptions off of that task. The Task wraps the <T> – it holds information about what happened when it returned the <T>.

Async CTP code looks like synchronous code except for the await and async keywords.

Previous convention was to write methods with the Async as the end of the method name. For example WriteAsync. The new paradigm is to write the method as WriteTaskAsync.

Everything after the await keyword is the continuation.

Multiple tasks in parallel… Task.WhenAll.  Or alternatively, Task.WhenAny.  NEAT!

Task based Async Patterns – continuation, cancellation, etc. Task.Wait(), AggregateException, ae.InnerExceptions, CancellationToken

Notes:  this is going to be a fun library to work with.  I can hardwly wait to get home and start coding!  That was not sarcasm but true enthusiasm.

Android Development for the .NET Developer

This is about native Android development, not developing using PhoneGap or MonoDevelop.

http://mike-marshall.net outlines the way to install the JDK, SDK, and everything you need to get an Android IDE up and running here.

  • android.app.Activity class
  • Combined with layouts (views), represents a single type of work that can be accomplished in your application
  • Reusable
    • Can be chained within your application to build a workflow
    • Can be published for use by other applications through :Intents” (more later)

Outlines how to create an Android Application Project within Eclipse.

The .net delegate event handler does not apply.

Working with resources can be annoying.

“Form” designer is very similar to XAML designer in visual studio.  Nothing is absolutely positioned unless you tell it to be as such.

Advertisements

What the heck is a ModelState error? Why do I care?

The following post is an email I sent out to my team reviewing why we care about ModelState in an Asp.NET MVC 3 project:

When you bind your views to a Model, you are basically telling MVC to keep track of all of the public properties in the class type that you bound the view to. When you send data to an mvc action via an HTTP request (POST, GET, PUT, DELETE, etc.), mvc uses a ModelBinder to take all the data you sent and shove it into the Model type that you specified as the parameters of the action. If there were any problems binding your data to the Model type specified, you get a model state error. Those errors are stored in the ModelState dictionary which is a key value pair collection where the key’s are all the propterty names of the binding type properties. If you encounter an error, the best practices scenario that MVC likes, is to return the invalid Model back to the View. When you do this, AND you have ClientValidationEnabled AND UnbotrusiveValidationEnabled AND you are using ValidationMessage or ValidationMessageFor, or ValidationSummary helpers on your form properites, wonderful things happen on the View; the error message of the Model State error is shown.

I want to point out another scenario which Rob [Gedelian] has taken advantage of. The preceding scenario involves ModelState binding errors, which only happen before the body of your Action code is executed. But what happens if you encounter an error, or an unexpected (but handled) situation in your action code. You can manually add a model state error to the collection. If you add the ModelState error using a key that is already on your form, you will be displaying back the error NEXT TO the invalid form property back on your view.

        [HttpPost]
        public void CreateDocumentAsync(EmployeeDocumentViewModel viewModel)
        {
            Request.Headers["X-Requested-With"] = "XMLHttpRequest"; // spoof ajax request headers in case of an error - we don't want to render the layout

            if (ModelState.IsValid && !FileUtils.IsValidDocument(viewModel.File.ContentType))
            {
                ModelState.AddModelError("File", "Invalid file type.  Please upload a document.");
            }

            if (ModelState.IsValid)
            {
                new EmployeeCreateDocumentService(AsyncManager, viewModel);
            }
            else
            {
                viewModel.New = true;
                viewModel.Error = true;
                this.AsyncManager.Parameters["viewModel"] = viewModel;
            }
        }

The “File” parameter is the key, which maps back to the view:

        @Html.EditorFor(e => e.File)
…
        <li class='validationSummary'>
            @Html.ValidationSummary()
        </li>

The way Rob chose to display the errors was using an Html.ValidationSummary helper, but he could just as easily used the following:

        @Html.EditorFor(e => e.File)
        @Html.ValidationMessageFor(e => e.File)

As an aside, the reason Rob was able to use Html.EditorFor is because I created an MVC Editor template for the type HttpPostedFileBase:

@model HttpPostedFileBase
 
@{
    var attrs = Html.Attributes();
    attrs = Html.AddMaxLengthAndRequiredToAttributes();
    attrs["class"] = "text-box single-line" + (attrs.ContainsKey("class") ? " " + attrs["class"] : string.Empty);
    attrs["type"] = attrs.ContainsKey("type") ? attrs["type"] : "file";
}
@Html.FileBox("", attrs)

e.target vs. e.currentTarget

I feel the need to explain the difference between e.target and e.currentTarget. There are subtle differences. Relying on e.target is NOT the way to go, and I tend to see over usage amongst the code that I review.

Consider the following markup:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Untitled Page</title>
    <style type="text/css">
        a {
            background: pink;
            padding: 10px;
        }
        span {
            background: yellow;
        }
    </style>
</head>
<body>
    <a href="#"><span>This is some content inside a link</span></a>
</body>
<script type="text/javascript" src="/Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="/Scripts/jquery.cookie.js"></script>
<script type="text/javascript" src="/Scripts/jquery.querystring.js"></script>
<script type="text/javascript">
    var debug = 'on';
</script>
<script type="text/javascript" src="/Scripts/log.js"></script>
<script type="text/javascript">
    $(function () {
 
        $('a').on('click', function (e) {
            /// <param name="e" type="jQuery.Event">jQuery Event Object</param>
            var target = e.target,
                $target = $(target),
                currentTarget = e.currentTarget,
                $currentTarget = $(currentTarget);
 
            $target.log('I am the target');
            $currentTarget.log('I am the currentTarget');
        });
 
    });
</script>
</html>

This renders the page like this:

If I click on the pink padding of the a, e.target and e.currentTarget are predictably the a.

If I click on the actual link which is really INSIDE the span, e.target and e.currentTarget are completely different.

The SPAN that you clicked on is the target. However, we bound the original event handler to the A. So if you wanted your event handler callback function to operate in reference to the A, you’re shit out of luck that you chose e.target in your code.

You might be asking, why not use “this”? I personally tend to shy away from using “this”, because you have to pay special attention to scope and closures. If you know what I’m talking about, then go right ahead and use “this”.

For arguments sake, here is the output when we add it to the code:

    $(function () {
 
        $('a').on('click', function (e) {
            /// <param name="e" type="jQuery.Event">jQuery Event Object</param>
            var target = e.target,
                $target = $(target),
                currentTarget = e.currentTarget,
                $currentTarget = $(currentTarget),
                $this = $(this);
 
            $target.log('I am the target');
            $currentTarget.log('I am the currentTarget');
            $this.log('I am this');
        });
 
    });

KNOW THIS!

A special note, I am using the scripts log.js and jquery.cookie.js to do some special logging stuff. You may have notice that I had a line of code that said var debug = ‘on’. Well, if this wasn’t set, I also could have added debug=on to my uri querystring and also turned on console logging. If you’re interested in those little tidbits, you can check out the attached project.

Download the content here

Develop for one, deploy to all – HTML5 and your mobile apps

I had the great pleasure of returning to my native California to attend the DevCon5 conference in Silicon Valley last week.  The primary focus was HTML5.  If you don’t know what HTML5 is, have a look at Wikipedia’s definition.  I’m going to give you a paraphrased definition that Paul Trani of Adobe provided:

HTML5 is not just markup.  HTML5 encompasses the new HTML doctype and associated HTML markup, CSS3 and JavaScript.

The conference was really like most others that I had been to, where it was hit or miss depending on which sessions you chose to go to.  The main takeaway was in the mobile development arena.  What the speakers generally were proposing was that you should develop your mobile applications using HTML5 using device native web views or use a wrapper like PhoneGap.  The benefit here really is develop for one, deploy to all.

It just so happens that on the plane ride back to Minneapolis, the traveler sitting next to me was Marc Grabanski of jQueryUI datepicker fame.  We talked about imperative vs. declarative js and his new company MJG International where he is doing exciting things with video training at Frontend Masters.  I took the opportunity of this chance meeting to share my experiences of the last few days regarding HTML5.

Here are a few points that I garnered:

  • His general feeling was that if you are going to wrap your mobile apps, don’t use PhoneGap… use Titanium.  Titanium provides a much deeper hook into a device’s built-in features.
  • Don’t use Sencha Touch.  Instead, use jQuery.mobile for your phone development.  While Marc seemed to be a jQuery.mobile evangelist, I think he has a good point.  Sencha was built for a desktop application developer in mind, NOT a web developer.
  • If you want to succeed, you must believe through and through in what you are doing. (while this is not developer related, I though it must be shared)  Personally, I would emphasize this point and say “let your passion run wild”.
  • Develop Mobile First.  Or even, Mobile For All.  Marc was showing me how he was using jQuery Mobile to develop an entire web site, basically using it as a templated website that scaled depending on device size.

I was also happy to discuss my recent blog post about jQuery UI unobtrusive with ajax support.  Based on that conversation, I’m probably going to do a re-write based on how Keith Wood’s Clean Calendar was doing the wiring up of the options.

All in all it was a great trip.  What I really want to do now however, is code…

jQuery Inline Editor plugin (source code)

Yesterday I talked about the inline editing paradigm that we are using for WebCenter 6. I have upgraded the plugin to follow the best practices for authoring a jQuery plugin.  The plugin now takes in methods and options.  I have exposed the methods “edit”, “cancel”, and “destroy” to allow for calling the edit and cancel functionality from outside the core function.  My next step will be to call the inline editing from within unobtrusive ajax onsuccess methods which I talked about before.

/*!
 * jQuery Inline Editor
 * Copyright 2011, Andrew Cohen https://omegaluz.wordpress.com
 */

(function ($) {

    var getSettingsElements = function (settings, context) {
        var display = $(settings.display, context);
        var edit = $(settings.edit, context);
        var editlink = $(settings.editlink, context);
        var cancellink = $(settings.cancellink, context);
        return {
            display: display,
            edit: edit,
            editlink: editlink,
            cancellink: cancellink
        };
    }

    /// <param name="$" type="jQuery">jQuery Object</param>
    var methods = {
        init: function (options) {

            return this.each(function () {

                var $this = $(this),
                     data = $this.data('inlineeditor'), // retrieve the settings that were previously stored
                     events,
                     settings;

                // If the plugin hasn't been initialized yet
                if (!data) {

                    var defaults = {
                        display: '[data-inlineeditor-display]',
                        edit: '[data-inlineeditor-edit]',
                        editlink: '[data-inlineeditor-editlink]',
                        cancellink: '[data-inlineeditor-cancellink]'
                    };

                    settings = $.extend(defaults, options);

                    events = {
                        editClick: function (e) {
                            /// <param name="e" type="jQuery.Event">jQuery Event Object</param>
                            e.preventDefault();

                            var $settings = getSettingsElements(settings, $this);
                            $settings.display.add($settings.editlink).hide();
                            $settings.edit.add($settings.cancellink).show();
                        },
                        cancelClick: function (e) {
                            /// <param name="e" type="jQuery.Event">jQuery Event Object</param>
                            e.preventDefault();

                            var $settings = getSettingsElements(settings, $this);
                            $settings.edit.add($settings.cancellink).hide();

                            var $form = $this.find('form');
                            $.validator.unobtrusive.parse($form);
                            if ($form.length > 0) {
                                var validator = $form.data('validator'); // get the jQuery.validate validator object for the form
                                if (validator) {
                                    validator.resetForm(); // reset the form using the validator
                                } else {
                                    $form[0].reset(); // reset using the form's built-in reset function
                                }
                            }

                            $settings.display.add($settings.editlink).show();
                        }
                    };
                    data = {
                        settings: settings,
                        events: events
                    };
                    // save the settings in the data
                    $(this).data('inlineeditor', data);

                } else {
                    settings = data.settings;
                    events = data.events;
                }

                // hide both the edit elements and the cancel link
                var $settings = getSettingsElements(settings, $this);
                $settings.edit.add($settings.cancellink).hide();

                // wire up the events
                $this.on('click.inlineeditor', settings.editlink, events.editClick);
                $this.on('click.inlineeditor', settings.cancellink, events.cancelClick);

            });
        },
        destroy: function () {
            return this.each(function () {

                var $this = $(this),
                     data = $this.data('inlineeditor');
                if (data) {
                    var settings = data.settings;
                    $this.off('.inlineeditor');
                    $this.removeData('inlineeditor');
                }

            })
        },
        edit: function () {
            return this.each(function () {

                var $this = $(this),
                    data = $this.data('inlineeditor');
                if (data) {
                    var settings = data.settings;
                    var $settings = getSettingsElements(settings, $this);
                    $settings.editlink.trigger('click');
                }

            })
        },
        cancel: function () {
            return this.each(function () {

                var $this = $(this),
                     data = $this.data('inlineeditor');
                if (data) {
                    var settings = data.settings;
                    var $settings = getSettingsElements(settings, $this);
                    $settings.cancellink.trigger('click');
                }

            })
        },
        close: function (context) {
            return this.each(function () {

                var $this = $(this),
                    data = $this.data('inlineeditor');
                if (data) {
                    var settings = data.settings;
                    var $settings = getSettingsElements(settings, $this);
                    $settings.edit.add($settings.cancellink).hide();
                    $settings.display.add($settings.editlink).show();
                }
            })
        },
        closeWhenValid: function () {
            return this.each(function () {

                var $this = $(this),
                     data = $this.data('inlineeditor');
                if (data) {
                    var $form = $this.find('form');
                    $.validator.unobtrusive.parse($form);
                    if ($form.length > 0) {
                        if ($form.find('.input-validation-error').length == 0) {
                            methods.close.apply($this, arguments);
                        }
                    }
                }

            })
        }
    };

    $.extend($.fn, {
        inlineeditor: function (method) {
            if (methods[method]) {
                return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
            } else if (typeof method === 'object' || !method) {
                return methods.init.apply(this, arguments);
            } else {
                $.error('Method ' + method + ' does not exist on jQuery.inlineeditor');
            }
        }
    });

} (window.jQuery));

Inline Editing paradigm using a jQuery Inline Editor plugin

As our WebCenter 6 project is nearing release, we’re constantly trying to make our code more DRY.  The basic premise of this post is this: how do we duplicate the showing and hiding of elements needed for inline form field editing without re-inventing the wheel.

What is this inline editing that I’m speaking of?  Well, consider this content:

Customer details pane from WebCenter 6

Customer details pane from WebCenter 6

Rather than creating a whole new page, to edit the Username and other information, why not just pop an edit link next to the Username and allow editing right there on the page?  This eliminates the need for creating a second page, popup, or what have you.  When the edit link is clicked, the display of the username turns into an editor.  An associated cancel link and Save button would also appear.

username edit link

username edit link

editor, save, and cancel link

editor, save, and cancel link

I can accomplish this pretty easily with some nifty jQuery code using hide, show, toggle, etc., but what I really want to do is write this code once and be able to re-use it for other forms that would use the exact same functionality.

Enter the jQuery plugin.

Our wonderfully talented UX developer, Pete Klein suggested we wire this up with data attributes.  Without delving into the details of writing a jQuery plugin, or really optimizing the code, here it is:

/*!
 * jQuery Inline Editor
 * Copyright 2011, Andrew Cohen https://omegaluz.wordpress.com
 */

(function ($) {
    /// <param name="$" type="jQuery">Description</param>

    $.fn.inlineeditor = function (options) {

        var $this = this;

        var settings = $.extend({
            display: this.find('[data-inlineeditor-display]'),
            edit: this.find('[data-inlineeditor-edit]'),
            editlink: this.find('[data-inlineeditor-editlink]'),
            cancellink: this.find('[data-inlineeditor-cancellink]'),
            form: this.find('form[data-val=true]')
        }, options);

        settings = $.extend(settings, this.data('settings')); // apply the settings that are stored in the data['settings'] object
        this.data('settings', settings); // store the current settings in the settings data object
        this.attr('data-inlineeditor', 'true');
        settings.edit.hide();
        settings.cancellink.hide();

        settings.editlink.on('click', function (e) {
            /// <param name="e" type="jQuery.Event">jQuery Event Object</param>
            var target = e.target;
            var $target = $(target);
            var currentTarget = e.currentTarget;
            var $currentTarget = $(currentTarget);

            e.preventDefault();

            settings.display.hide();
            settings.editlink.hide();

            settings.edit.show();
            settings.cancellink.show();
        });
        settings.cancellink.on('click', function (e) {
            /// <param name="e" type="jQuery.Event">jQuery Event Object</param>
            var target = e.target;
            var $target = $(target);
            var currentTarget = e.currentTarget;
            var $currentTarget = $(currentTarget);

            e.preventDefault();

            settings.edit.hide();
            settings.cancellink.hide();

            var $form = $this.find('form');
            if ($form.length > 0) {
                var validator = $form.data('validator');
                if (validator) {
                    validator.resetForm();
                }
            }

            settings.display.show();
            settings.editlink.show();
        });
        /*// is the below code more efficient?
        this.on('click', settings.editlink.selector, function (e) {
        /// <param name="e" type="jQuery.Event">jQuery Event Object</param>
        e.preventDefault();
        settings.display.hide();
        settings.editlink.hide();
        settings.edit.show();
        settings.cancellink.show();
        });
        this.on('click', settings.cancellink.selector, function (e) {
        /// <param name="e" type="jQuery.Event">jQuery Event Object</param>
        e.preventDefault();
        settings.edit.hide();
        settings.cancellink.hide();
        settings.display.show();
        settings.editlink.show();
        });
        */

    };

} (window.jQuery));

Interesting to note, I’m making use of the new jQuery.on function instead of using click, bind, or live.

This code assumes the following:

  • Plugin and all associated functionality are instantiated like so: $(‘#sampleeditor’).inlineeditor();
  • There is an encapsulating element from which all other elements are nested.
  • Within the root there exists ‘[data-inlineeditor-display]’, ‘[data-inlineeditor-editlink]’, ‘[data-inlineeditor-edit]’, ‘[data-inlineeditor-cancellink]’.
  • ‘[data-inlineeditor-display]’ is an element that contains the original text
  • ‘[data-inlineeditor-editlink]’ is a link that when clicked hides the display and shows the editor
  • ‘[data-inlineeditor-edit]’ is a form input that serves to edit the content
  • ‘[data-inlineeditor-cancellink]’ cancels out of the editor, reset’s the form, hides the editor and shows the display again

My mvc 3 razor/html markup looks like so:

        <li><span class='key lfloat'><strong>Username:</strong></span>
            <span class='value lfloat' id="usernameeditor">
                <span data-inlineeditor-display>@Model.User.UserName</span>
                <a data-inlineeditor-editlink href="#">Edit</a>
                <span data-inlineeditor-edit id='usernameEdit'>
                    @{
                        Html.RenderPartial("RenameUserControl", Model.UserRenameViewModel);
                    }
                </span>
                <a data-inlineeditor-cancellink href="#">Cancel</a>
            </span>
            <script type="text/javascript">
                $(function () {
                    $('#usernameeditor').inlineeditor();
                });
            </script>
            <div class='clear'>
            </div>
        </li>

The content of the RenameUserControl:

@model UserRenameViewModel

@using (Ajax.BeginForm("RenameUser",
    "Home",
    null,
    new AjaxOptions
    {
        HttpMethod = "POST",
        UpdateTargetId = "usernameEdit"
    },
    new { id = "renameUserForm" }))
{
        @Html.HiddenFor(model => model.UserID)
        @Html.HiddenFor(model => model.UserName)
        <span class="editor-field">
            @Html.EditorFor(model => model.NewUserName)
            @Html.ValidationMessageFor(model => model.NewUserName)
        </span>

        @Html.ValidationSummary(true)

        <input type="submit" value="Save" />
}

<script type="text/javascript">
    $(function () {
        $.validator.unobtrusive.parse('#renameUserForm');
    });
</script>

Interesting to note, we’re using MVC 3’s built in unobtrusive ajax with data annotations to accomplish the actual form submission.  Again, I didn’t have to write any javascript to wire that up.

I can now re-use this plugin wherever we’re doing inline editing on our site.  I’ll still need to hook into my client side and server side validation when I’m clicking the save button.  I’ll probably wire up an onsuccess event to check whether there are any validation errors and then if not, fire some kind of hide event, rather than the plugin’s cancel code.

** I have updated the source for this. You can find it here.

Unobtrusive jQuery UI with AJAX support

Recently I came across a post by Joe Stagner that talked about the practice of “Unobtrusive JavaScript” in web pages.  Assuming that you understand the separation of concerns therein, I’m going to jump right to a jQuery plug-in authored by Damian Edwards that is available on NuGet, Unobtrusive jQuery UI.

The main idea is this: you can add markup to your html content that wires up jQuery UI without the need to write any additional javascript; just by virtue of including the plug-in script in your html, you can wire up jQuery UI widgets.

Normally, to wire up the following:

jQuery DatePicker

jQuery DatePicker

You would need to write this code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link href="Content/themes/base/minified/jquery-ui.min.css" rel="stylesheet" type="text/css" />
    <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery-ui-1.8.16.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $('#date').datepicker({});
        });
    </script>
</head>
<body>
    <input type="text" name="date" id="date" />
</body>
</html>

The plug-in he wrote is fantastic in that it does the job with a minimal amount of effort.  But, it doesn’t address any content that was added AFTER the page has loaded via AJAX.  This is because his plugin wires everything up in jQuery’s document.ready event.  The other limitation to his code is that it did not correctly parse options for jQuery UI widgets that were camelCased.

So if there was an option like changeMonth, the attribute should be data-ui-datepicker-changeMonth.  However, the browser will render this as data-ui-datepicker-changemonth without the uppercased M.  This poses a problem in that JavaScript is a case-sensitive language and that option will be passed to the jQuery UI widget function like:

    <input type="text" name="date" id="date" data-ui-fn="datepicker" data-ui-changeMonth="true" />

will functionally get evaluated as:

    $('#date').datepicker({
        changemonth: true
    });

When in fact what we need is:

    $('#date').datepicker({
        changeMonth: true
    });

Check out his source:

/*!
 * Unobtrusive jQuery UI 0.1
 * Copyright 2011, Damian Edwards http://damianedwards.com
 * Licensed under Ms-PL
 * http://www.opensource.org/licenses/MS-PL
 */
(function ($) {
	"use strict";

    $(function () {
        var prefix = "data-ui-";

        // Wire-up jQuery UI unobtrusively
        $("*[" + prefix + "fn]").each(function () {
            var el = this,
                $el = $(el);

            // Loop through functions in data-ui-fn attribute
            $.each($el.attr(prefix + "fn").split(" "), function () {
                var fn = this,
                    options = {},
                    optionPrefix = prefix + fn + "-";

                // Build options parameter from data-ui-[fn]-* attributes
                $.each(el.attributes, function () {
                    var attr = this;
                    if (!attr.specified) return true;

                    if (attr.name.indexOf(optionPrefix) === 0) {
                        options[attr.name.substr(optionPrefix.length)] = attr.value;
                    }
                });

                // Call jQuery UI fn if it exists
                ($el[fn] || $.noop).call($el, options);
            });
        });
    });

}(window.jQuery));

Yesterday I proposed an update that would do the following:

  1. Add a method that allowed to parse the an element an all of it’s children in the hierarchy of the DOM
  2. Add a method that parses a specific element in the DOM
  3. Correct the parsing of the options for the jQuery UI widget function.  Fix camel casing.

Here is what I came up.  You should note, that I modeled this after the default jquery.validate.unobtrusive.js code that is in any default MVC project.

/*!
* Unobtrusive jQuery UI 0.1
* Copyright 2011, Damian Edwards http://damianedwards.com
* Licensed under Ms-PL
* http://www.opensource.org/licenses/MS-PL
*/

/*!
* Modified by Andrew Cohen, 11/30/2011
* TempWorks Software, Inc.
*/

(function ($) {
    "use strict";

    var $jQui = $.ui,
        prefix = "data-ui-";

    $jQui.unobtrusive = {
        parse: function (element) {
            // Wire-up jQuery UI unobtrusively
            $("*[" + prefix + "fn]", element).each(function () {
                $jQui.unobtrusive.parseElement(this);
            });
        },
        parseElement: function (el) {
            var $el = $(el),
                el = $el[0];

            // Loop through functions in data-ui-fn attribute
            $.each($el.attr(prefix + "fn").split(" "), function () {
                var fn = this,
                    options = {},
                    optionPrefix = prefix + fn + "-";

                // Build options parameter from data-ui-[fn]-* attributes
                $.each(el.attributes, function () {
                    var attr = this;
                    if (!attr.specified) return true;

                    if (attr.name.indexOf(optionPrefix) === 0) {
                        // camelCase the name
                        var attrName = $.camelCase(attr.name.substr(optionPrefix.length));
                        options[attrName] = attr.value;
                    }
                });

                // get UI fn if it exists
                var uiFn = ($el[fn] || $.noop);
                // call destroy to remove the ui widget
                uiFn.call($el, 'destroy');
                // call fn with options
                uiFn.call($el, options);
            });
        }
    }

    $(function () {
        $jQui.unobtrusive.parse(document);
    });

} (window.jQuery));

It also has 2 new methods:

$.ui.unobtrusive.parse

and

$.ui.unobtrusive.parseElement

The two new methods allow you to re-parse the DOM after content has been added to your page via AJAX.

I have submitted this change to Damian’s GitHub repository.

An exploration of HTML5 Editor Templates with MVC

It occurred to me that we should be using the input type = email in our WebCenter 6 project.  I thought editor templates would be the right way to do this.

If you download the rtm sources for asp.net who will find the MVC 3 Futures source.  This has 2 interesting folders, DisplayTemplates and EditorTemplates inside a folder called DefaultTemplates.  Whenever you use Html.DisplayFor or Html.EditorFor, these templates are used.   You don’t have to download these templates for editor for or default for to work, the code for these is actually packed inside a resource file inside the mvc assembly.  You also might want to check out the source for these.

Default Templates Folder

I wanted to check to see if there was a template for an EmailAddress.  Interestingly, I found a Display template, but not an Editor template.

Display Templates

The display template for email looks like this:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<a href="mailto:<%= Html.AttributeEncode(Model) %>"><%= Html.Encode(ViewData.TemplateInfo.FormattedModelValue) %></a>

You can see that all it does is add a mailto link.

I started first by creating an EditorTemplates folder inside of our root Views/Shared folder.  Then I created a partial view control named EmailAddress.  I names it email address because editor and display templates are used according to the following rules:

http://scottonwriting.net/sowblog/archive/2011/11/22/using-templates-to-display-boolean-values-as-yes-no-options.aspx?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+ScottOnWriting+%28Scott+on+Writing%29

Specifically, the Html.DisplayFor and Html.EditorFor methods consult the following metadata in this order:

  1. The UIHint attribute – specifies the name of the template to use.
  2. The DataType attribute
  3. The data type

The data type is set from the DataAnnotations attribute:

        [DataType(DataType.EmailAddress)]

The partial view will be exactly the same as the editor template for a string except that the type will be changed.

Here is the string control:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>

<%= Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "text-box single-line" }) %>

But my email address control is going to do this with razor:

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "text-box single-line", type = "email" }) %>

Here is what validation looks like before I saved this template:

WebCenter 6 Your Profile Validation

Here is what it looks like afterwards.  I have to first change the code from;

                @Html.TextBoxFor(m => m.EmailAddress)

To

                @Html.EditorFor(m => m.EmailAddress)

Now I get this using FireFox.  The RED outline occurs because now I am using an editor template, which puts the correct validation classes:

Shared.css line 3392

.input-validation-error {
    background-color: #FFEEEE;
    border: 1px solid #FF0000;
}

WebCenter 6 Your Profile Validation 2

Interestingly enough, this is still not using HTML 5 validation.  The reason being there is a novalidate attribute on the form:

<form method="post" id="email-form" data-ajax-update="#change-form-email" data-ajax-success="Profile.changeSuccess" data-ajax-mode="replace" data-ajax-method="POST" data-ajax-begin="Modal.Loader.showTop" data-ajax="true" action="/Default/Account/ChangeEmail" style="display: block;" novalidate="novalidate">    <br>
    <div>
        <fieldset>
            <label class="editor-label" for="EmailAddress">New Email Address:</label>
            <div class="editor-field">
                <input type="email" value="" name="EmailAddress" id="EmailAddress" data-val-required="The Email Address field is required." data-val-email="The Email Address field is not a valid e-mail address." data-val="true" class="text-box single-line input-validation-error">
                <span data-valmsg-replace="true" data-valmsg-for="EmailAddress" class="field-validation-error"><span for="EmailAddress" generated="true" class="">The Email Address field is not a valid e-mail address.</span></span>
            </div>

            <div class="form-controls">
                <input type="submit" value="Change Email">
                <input type="button" class="change-cancel" value="Cancel">
            </div>
        </fieldset>
    </div>
</form>

This novalidate attribute is added by jquery.validate line 32:

// Add novalidate tag if HTML5.
this.attr('novalidate', 'novalidate');

According to w3schools:

novalidate novalidate Specifies that the form should not be validated when submitted

If I remove the novalidate attribute using firebug and then try to submit the form:

WebCenter 6 Your Profile Validation 3

The problem that I want you all to think about or research is:

How do we turn jquery validate on or off conditionally based on whether or not html 5 validation will work?  Modernizr gives you test’s for each individual input type, but how do you turn validation ON programatically when html 5 validation has been disabled using the novalidate attribute.  Try it out.

Furthering this, I then realized that there is a Nuget package that adds all of the HTML 5 editor templates.  It actually uses the exact same code that I came up with.  I’m going to add it to our project and see what happens.

https://github.com/srkirkland/Html5MvcTemplates

Html5MvcTemplates

There are also a ton of open source projects out there for Html 5 and mvc 3.  I wouldn’t be surprised if they are going to be built in to Mvc 4.  There is also the HTML 5 mvc 3 helpers which I’m guessing add this kind of code for non editor templates and display templates, using plain old Html.TextBox like syntax:

http://mvchtml5.codeplex.com/

https://github.com/Gutek/MVC-3-Html5EditorFor

Unobtrusive Validation with MVC 3 and Html.BeginForm

Yesterday a colleague of mine and I were trying to find out why client side unobtrusive validation attributes were being generated everywhere EXCEPT one specific page on our upcoming release of WebCenter 6.  Client side validation attributes in MVC 3 are html 5 data-val-*attributes.   They enable you to tie your validation to Data Annotation attributes on your models without having to write a line of javascript code.  This is sweet in my book because the JavaScript is completely decoupled from the actual C# code.

Here is what they look like:

<input type="text"
    name="UserName"
    data-val-required="The Username field is required."
    data-val="true"
    class="text-box single-line" />
  • data-val turns unobtrusive validation on for the input
  • data-val-required enables the required validation rule to kick in with the specified error message you see above

If you want to go into more detail, check out Brad Wilson’s in depth post about Unobtrusive Client Validation in ASP.NET MVC3.

The specific problem we were both encountering was that these attributes were simply not being output on our view when rendered in the browser.

I peeked into the source of System.Web.Mvc.dll and here is what I discovered.

  1. When you render an input using an HtmlHelper like @Html.EditorFor, @Html.TextBox etc., they are rendered with the InputExtensions.InputHelper method.
  2. InputHelper calls HtmlHelper.GetUnobtrusiveValidationAttributes to render the data-val attributes.
  3. GetUnobtrusiveValidationAttributes calls ViewContext.GetFormContextForClientValidation which checks to see if ClientValidation is enabled in the either your web.config or the scope of the view that you are rendering.
  4. GetFormContextForClientValidation will return the FormContext that was instantiated with @Html.BeginForm OR return null.
  5. If it returns null, no attributes are rendered, thus the need for Html.BeginForm.

So to re-cap.  I discovered the problem was that my colleague had NOT created his form using Html.BeginForm.  Instead, he had manually added a <form> tag, which in turn never created the ViewContext.FormContext object.

If you want to see for yourself, go download the latest MVC 3 sources from the ASP.Net site on CodePlex.

In my opinion, this is totally ridiculous.  And I guess the devs over at Microsoft agree because they are removing this requirement in MVC 4.

Here are Brad’s own words:

Important note: jQuery Validate requires your input elements to be inside of a <form> element in order to be validated. In addition, MVC 3 requires that you have called Html.BeginForm() to render this form, so that it can find its book-keeping object to help render the HTML attributes. Starting with MVC 4, we’ve eliminated the need for Html.BeginForm(), but the requirement for the HTML <form> element is still there.

Getting your data onto Windows Phone 7

Now that Microsoft has officially launched it’s latest incarnation of the mobile phone officially called Windows Phone 7 (WP7), what does that mean to all of us developers?

The biggest thing – you have to develop applications in Silverlight.  But not just any Silverlight, the version for use on WP7 is a subset hybrid between Silverlight 3 and 4.  I personally feel this is Microsoft’s way of promoting it’s slick looking implementation of a rich internet application (RIA) of which Silverlight’s main competitor is Adobe’s Flash Player.  If you’re interested, hop on over to http://riastats.com for the latest browser statistics.

When I first heard that WP7 was going to use Silverlight as a user interface, I was pretty ecstatic.  But when I was up at the Microsoft Campus in Redmond last month, I started drilling some of Microsoft’s developers; I wanted to know if I was going to be able to develop a Silverlight Application that would be internet browseable on a desktop using Internet Explorer, Firefox or Chrome and still be viewable on the WP7.   To their reluctance they admitted that this was not the case.  So let me put it this way… If you’re using the native Internet Explorer browser on a WP7 device and you navigate to a page that has Silverlight – let’s say http://www.microsoft.com – no Silverlight content will be displayed!  That sounds completely insane.  But I guess that’s another issue.  For now, we’re going to have to develop dedicated applications for WP7 following the same paradigm that Apple’s iPhone and Google’s Droid has done – a proprietary development platform for their phone.

So what can a developer do on this great new platform?  One cool feature is the ability to develop games that work on WP7 and Xbox.  But what else?  As a recent online article suggests, the hottest apps are social networking, news, and multimedia related.

But as a developer for line of business applications, my scope of vision always seems to focus on one thing – DATA.  How do I get the data that I want, and how should I display it in a way that makes sense – not just to me, but to the end-user?  Good UI design aside, I wanted to focus on the former – how do I get that data?

Well, it was Wednesday and the CEO of TempWorks received a package that contained a brand new Windows Phone 7 by Samsung.  Gregg opens the box, pulls out the phone, turns to me and says, “Andy, this week you’re only allowed to spend 40 hours on AppPortal – the rest of your dev time I want you to build me a Windows Phone app.”  And so it goes…  On Saturday I set out to do just that – goal in mind – build a windows phone app that displays a list of customers from one of our development databases.

When I was at the Microsoft Patterns & Practices Symposium, one of the best sessions  was “Open Data, Open Applications” by Don Box.  The session touted OData – or the Open Data Protocol (http://www.odata.org).  According to the OData website:

“The Open Data Protocol (OData) is a Web protocol for querying and updating data that provides a way to unlock your data and free it from silos that exist in applications today. OData does this by applying and building upon Web technologies such as HTTP, Atom Publishing Protocol(AtomPub) and JSON to provide access to information from a variety of applications, services, and stores.”

Don made publishing a database to a web service look so easy that I just had to try it.  And in fact, in a matter of minutes I was able to use Visual Studio to expose a SQL database table to a WCF/OData web service that made my data available to the Windows Phone.  In fact, if you check out the OData project on Codeplex (http://odata.codeplex.com/releases/view/54698) you can find a quick and dirty Visual Studio Project that will do just what I set out to do.

image

So now we have the base prototype for the next generation of TempWorks Mobile specifically made for Windows Phone 7!  Woohoo, hours of coding fun in the future!

There you have it.  Now I’m going to figure out how to secure my data on the phone!