Monday, March 26, 2012

Pinning a website - Part 1 - Internet Explorer 9

While attending a Webcamp around HTML 5, the instructor pointed out the "Pin to Taskbar" feature that is available as from Internet Explorer 9. Pinning a site to the taskbar makes your website behave more like a desktop application, allowing users to select from fixed tasks and/or a dynamic jumplist, receive notifications, see thumbnail previews... all available from a prominent location on screen showing your website's logo.

My blog pinned to my Taskbar

You can find all information and guidance on the 'Build my Pinned Site' website. Obviously I had to try it out for myself so if you are on Internet Explorer 9 or higher, you should be able to pin my blog to your taskbar. The result of doing this should look like this at the moment:

  • My brand new logo always present on the desktop
  • The right-click menu containing:
    • A link to my homepage
    • A fixed 'Tasks' section showing a link to my LinkedIn profile
    • A dynamic jumplist with my 10 most recent posts
As long as you don't pin this blog to your taskbar you will see a teaser bar at the bottom of my page informing you that this site can take advantage of the 'Pin to taskbar' feature

Generating the script

Microsoft provides a quick way of generating the script that is needed to enable the feature. When you start their wizard you'll need to provide some basic information, a list of fixed tasks, upload a 64x64 icon file, indicate if you want a teaser bar and give the URL to your RSS or Atom feed to generate the dynamic jump list. This generates a single JavaScript file that is hosted on the 'BuildMyPinnedSite' data servers, along with the icon you uploaded. So all you need to do is insert a reference to this script file on your page and you are good to go.

Unfortunately when I first inserted that script in my blog there were some issues:

  • The teaser bar was inserted on a fixed position on the top of the page where it collided with the Google navigation bar.
  • The URLs in my dynamic jumplist pointed to the 'comments' pages instead of the posts themselves.
  • I linked to the JavaScript file from within my blogspot template file, meaning that I would lose it if I were to choose a different template.

Making it work on Blogspot

Blogspot allows inserting custom HTML and JavaScript via their 'HTML/JavaScript' gadget. You can find it when you put your blog in design mode, choose layout and click 'Add Gadget'. I choose a wide gadget at the bottom of my screen because the generated teaser bar is quite wide.

Since the script has to do everything by itself, the entire construction of the teaser bar is done via script. I don't need that kind of dynamic behavior on this blog so I extracted the teaser bar <div id="___ie9sitepinning__bar_container"> from JavaScript and converted it to HTML. I also don't want the teaser bar to decide its own position. It should display in the area that is reserved for the gadget as defined by the template and chosen by the user.

These are the changes I made to the inline style of the root div:

  • Changed the style so it gets positioned inside the gadget's area
    • from "position: absolute; top: 0; left: 20px;width: 95%;"
    • into "position: relative; top: 0; left: 0px;width: 100%;"
  • Add the "display:none;" style because I don't want this div to appear by default
The HTML that I put in 'HTML/JavaScript' gadget looks like this:

<div id="___ie9sitepinning__bar_container" style="display:none; position: relative; top: 0; left: 0px;width: 100%; margin: 0; padding: 0; border: 0 none; border-bottom: 1px solid #707070;color: #1c1f26; background: transparent none no-repeat scroll 0 0; font-family: 'segoe ui', Arial, tahoma, sans-serif;line-height: 18px; box-shadow: 0 1px 5px rgba(140,140,140,0.7);">
 <div style="border: 1px solid #E1E1E1; padding: 5px 9px 2px 9px; background: #fff url(http://www.buildmypinnedsite.com/PinImages/Bar/bar-background.png) repeat-x scroll 0 100%;">
  <table cellspacing="0" cellpadding="0" style="width: 100%; border: 0 none; border-collapse: collapse;">
   <tbody>
    <tr>
     <td>
      <div style="background: transparent url(http://ie9pinning.blob.core.windows.net/files/JumpList/634679315872229742/Main-c:/users/bart.jolling/pictures/bscb-logo.png) no-repeat scroll 0 3px;background-size: 20px 20px; width: 260px; padding-left: 26px; min-height: 30px;font-weight: bold; font-size: 14px;">
       Experience my Software Cookbook as a Pinned Site
      </div>
     </td>
     <td>
      <div style="display: inline-block; padding-right: 40px; position: relative; text-align: right;">
       <strong style="font-weight: bold; font-size: 18px;">Drag this icon to your taskbar
        <img src="http://www.buildmypinnedsite.com/PinImages/Bar/arrow-icon.png" alt="Arrow" />
       </strong>
       <div style="color: #797c85; font-size: 12px;">
        or, <a href="#" onclick="window.external.msAddSiteMode(); return false" style="color: #6CABBA;text-decoration: underline;">click here</a> to add this site to your start menu
       </div>
       <div style="position: absolute; right: -120px; top: -13px; width: 164px; height: 143px;background: transparent url(http://www.buildmypinnedsite.com/PinImages/Bar/drag-icon-placeholder.png) no-repeat scroll 0 0;">
        <img class="msPinSite" style="position: absolute; top: 17px; left: 16px; cursor: move;width: 32px; height: 32px;" src="http://ie9pinning.blob.core.windows.net/files/JumpList/634679315872229742/Main-c:/users/bart.jolling/pictures/bscb-logo.png" alt="Drag this icon to pin this site" />
       </div>
      </div>
     </td>
     <td>
      <div style="position: relative; float: right; width: 80px; min-height: 30px; padding-left: 23px;padding-right: 30px; background: transparent url(http://www.buildmypinnedsite.com/PinImages/Bar/info-icon.png) no-repeat scroll 0 6px;">
       <a style="font-size: 12px; color: #6CABBA; text-decoration: underline;" href="http://windows.microsoft.com/en-US/internet-explorer/products/ie-9/features/pinned-sites" target="_blank">Learn about Site Pinning</a>
       <div onclick="document.getElementById('___ie9sitepinning__bar_container').style.display='none';window.sessionStorage.setItem('hideie9sitepinningbar', '1')"
        style="background: transparent url(http://www.buildmypinnedsite.com/PinImages/Bar/close-button.png) no-repeat scroll 0 0;position: absolute; top: 0; right: 0; display: block; width: 18px; height: 18px;cursor: pointer; float: right;">
       </div>
      </div>
     </td>
    </tr>
   </tbody>
  </table>
 </div>
</div>

Notice that the image on the highlighted line 20 has a class attribute set to "msPinSite". This class is recognized by Internet Explorer 9 and higher and enables the 'Drag this icon to your taskbar' functionality

The rest of the JavaScript needs to be encapsulated in a CDATA block and appended below the above div. Notice the two changes (highlighted) I had to make:

Line 87-99

The original code for generating the jumplist downloads the list of links per post and then just takes the first available link. This happens to be the link to the comments page of each blog. According to the information I found on the structure of an Atom feed (as used by blogspot) the perma-link to a post is called the 'alternate' link. So I execute a 'filter' function to the list of links to find the alternate link. If it can't find it, I take the first link just like the original code did

Line 171-172

Instead of dynamically generating the div here, I just find it back using its 'id' and I set the 'display' style to 'block'

<script type='text/javascript'>
//<![CDATA[
    var ____prototype_ae_IE9JumpList = ____prototype_ae_IE9JumpList || {};

    (function (jumplist) {
        if (!navigator.userAgent.toLowerCase().match(/msie (9|10)(\.?[0-9]*)*/)) {
            return;
        }

        var options = {

            // Basic site information 
            siteName: 'Bart\'s Software Cookbook', // Site Name
            applicationName: 'Bart\'s Software Cookbook', // Site Name 
            startURL: 'http://bartjolling.blogspot.com/', // Homepage URL 
            shortcutIcon: 'http://ie9pinning.blob.core.windows.net/files/JumpList/634679315872229742/Main-c:/users/bart.jolling/pictures/bscb-logo.ico', // Main Site Icon
            tooltip: '',

            // Dynamic jumplist tasks & notifications
            rssFeedURL: 'http://www.buildmypinnedsite.com/RSSFeed?feed=http%3a%2f%2fbartjolling.blogspot.com%2ffeeds%2fposts%2fdefault',
            categoryTitle: 'Posts', // Task group name
            defaultTaskIcon: 'http://ie9pinning.blob.core.windows.net/files/JumpList/634679315872229742/GenericTask-c:/users/bart.jolling/pictures/feed.ico', // Generic task icon

            navButtonColor: false,

            // Jumplist tasks { name: Task Label, action: Task URL, icon: Task Icon }
            staticTasks: [{ name: 'Linked-In Profile', action: 'http://www.linkedin.com/in/bartjolling', icon: 'http://ie9pinning.blob.core.windows.net/files/JumpList/634679315872229742/Task0-c:/users/bart.jolling/pictures/linkedin.ico', target: 'tab'}],

            // Drag and drop site pinning bar  
            prompt: true, // Add a site pinning bar on top of my site pages
            barSiteName: 'Bart\'s Software Cookbook' // Site name as it should appear on the pinning bar
        };

        var lib = {
            dom: {
                meta: function (name, content) {
                    var meta = document.createElement('meta');
                    meta.setAttribute('name', name);
                    meta.setAttribute('content', content);
                    return meta;
                },
                link: function (rel, href) {
                    var link = document.createElement('link');
                    link.setAttribute('rel', rel);
                    link.setAttribute('href', href);
                    return link;
                },
                div: function () {
                    return document.createElement('div');
                }
            },
            net: {
                getJSONP: function (URL) {
                    var script = document.createElement('script');
                    script.type = 'text/javascript';
                    script.src = URL + (URL.indexOf('?') != -1 ? '&' : '?') + Date.now();
                    var head = document.getElementsByTagName('head')[0];
                    head.insertBefore(script, head.firstChild);
                }
            }
        };

        jumplist.parseRSSFeed = function parseRSSFeed(news) {
            try {
                if (window.external.msIsSiteMode()) {
                    window.external.msSiteModeClearJumpList();
                    window.external.msSiteModeCreateJumpList(options.categoryTitle);

                    try {
                        // RSS feeds
                        if (news.rss && news.rss.channel && news.rss.channel.item) {
                            for (var items = news.rss.channel.item.slice(0, 10), numItems = items.length, i = numItems - 1, task, pubDate, taskTitle = ''; i >= 0; i--) {
                                task = items[i];
                                pubDate = Date.parse(task.pubDate);
                                taskTitle = task.title ? (typeof task.title == 'string' ? task.title : task.title['#cdata-section'] || '') : '';
                                window.external.msSiteModeAddJumpListItem(taskTitle, task.link, options.defaultTaskIcon);
                            }
                        } else if (news.feed && news.feed.entry) { // Atom feeds
                            for (var items = news.feed.entry.slice(0, 10), numItems = items.length, i = numItems - 1, task, pubDate, taskTitle = '', link = {}; i >= 0; i--) {
                                task = items[i];
                                pubDate = Date.parse(task.published);
                                taskTitle = task.title ? (typeof task.title == 'string' ? task.title : (task.title['#cdata-section'] ? task.title['#cdata-section'] : task.title['#text'] || '')) : '';

                                if (task.link) {
                                    if (typeof task.link == 'string') {
                                        link['@href'] = task.link || '#';
                                    } else if (Object.prototype.toString.call(task.link) === '[object Array]') {
                                         //filter to get the perma link called 'alternate'
                                        links = task.link.filter( function (item) {
                                            return(item['@rel'] == 'alternate');
                                        });
                                        if(links[0]) {
                                          link = links[0];
                                        } else {
                                          link = task.link[0];
                                        }
                                    } else {
                                        link = task.link;
                                    }
                                }

                                window.external.msSiteModeAddJumpListItem(taskTitle, link['@href'] || '#', options.defaultTaskIcon);
                            }
                        }
                    } catch (ex) {
                    }

                    window.external.msSiteModeShowJumpList();
                } else {
                }
            }
            catch (ex) {
            }
        }

        // Init code
        document.addEventListener('DOMContentLoaded', function () {

            try {
                document.getElementsByTagName('body')[0].onfocus = function () {
                    window.external.msSiteModeClearIconOverlay();
                };
            } catch (err) {
            }

            var head = document.getElementsByTagName('head');

            if (!head) {
                return;
            }

            head = head[0];

            var links = document.getElementsByTagName('link'), remove = [];

            for (var i = 0, rel; i < links.length; i++) {
                rel = links[i].getAttribute('rel');
                if (!rel) {
                    continue;
                }
                rel = rel.toLowerCase().replace(/^\s+|\s+$/g, '').replace(/\s+/g, ' ');
                if (rel == 'icon' || rel == 'shortcut icon') {
                    remove.push(links[i]);
                }
            }

            for (i = 0; i < remove.length; i++) {
                head.removeChild(remove[i]);
            }

            if (options.shortcutIcon) {
                head.appendChild(lib.dom.link('shortcut icon', options.shortcutIcon));
            }

            head.appendChild(lib.dom.meta('application-name', options.applicationName));
            head.appendChild(lib.dom.meta('msapplication-tooltip', options.tooltip));

            if (options.navButtonColor) {
                head.appendChild(lib.dom.meta('msapplication-navbutton-color', options.navButtonColor));
            }

            if (options.startURL) {
                head.appendChild(lib.dom.meta('msapplication-starturl', options.startURL));
            }

            for (var i = 0, task; i < options.staticTasks.length; i++) {
                task = options.staticTasks[i];
                head.appendChild(lib.dom.meta('msapplication-task', 'name=' + task.name + ';action-uri=' + task.action + ';icon-uri=' + task.icon + ';window-type=' + task.target));
            }
            if (options.prompt && !window.external.msIsSiteMode() && sessionStorage.getItem('hideIE9SitePinningBar') != '1') {
                var bar = document.getElementById('___ie9sitepinning__bar_container');
                bar.style.display='block';
            }

            jumplist.poll = function () {
                lib.net.getJSONP(options.rssFeedURL, jumplist.parseRSSFeed);
            };

            window.setTimeout(jumplist.poll, 30);
        });
    })(____prototype_ae_IE9JumpList);
//]]>
</script>

Pinning my blog site seems a bit over the top but I can easily imagine business cases for this feature. Web applications are starting to behave more and more like desktop applications and this is one of the things that makes the end-user experience richer and provides the content owner with a means to grab the users' attention and get them to visit their site more frequently.

Thursday, March 15, 2012

Building Single Page Apps with ASP.NET MVC4 - Part 3 - Basic Mobile Application

This blog is part of a series about building Single Page Applications using ASP.NET MVC 4 beta. When writing this post I assumed you have read the first and second posts. The code snippets are just the incremental changes that are needed since the second post

  1. Single Page Applications - Part 1 - Basic Desktop application
  2. Single Page Applications - Part 2 - Advanced Desktop Application
  3. Single Page Applications - Part 3 - Basic Mobile Application
  4. Single Page Applications - Part 4 - Sorting, Filtering and Manipulation data with upshot.js
  5. Single Page Applications - Part 5 - With MVC4 RC

The mobile viewmodel

In this post I'm adding a mobile component to the DeliveryTracker application I have been describing in my previous posts. I want to have an overview page per delivery, an overview page per customer and a detail view for the currently selected delivery. In order to do that, I'll create a new MobileDeliveriesViewModel in the DeliveriesViewModel.js file. This new class inherits from the existing DeliveriesViewModel class to inherit the existing features but adds some of its own:

  • self.currentDelivery is an observable (knockout.js) variable to keep track of the currently selected delivery which we need in order to navigate from the overview pages to the detail page
  • self.nav keeps the navigation history (nav.js) for our single page. It gives the impression to the user of navigating between different pages as usual. But it enables back button and allows creation of bookmarks within the single page application.
    • The name of the view will be stored in the view parameter. The default page will be the deliveries view.
    • A deliveryId paramater will be included in the querystring and intialized to null
    • On navigation we extract the deliveryId from the querystring and use it to filter the datasource
  • self.showsomething functions to invoke the navigation functionality. The showDelivery function receives the delivery object that was clicked so it can extract the deliveryId from it and attach it to the querystring so the delivery view can read it.
function MobileDeliveriesViewModel() {
  //inherit from DeliveriesViewModel
  var self = this;
  DeliveriesViewModel.call(self);

  // Data
  self.currentDelivery = ko.observable();

  self.nav = new NavHistory({
      params: { view: 'deliveries', deliveryId: null },
      onNavigate: function (navEntry) {
          var requestedDeliveryId = navEntry.params.deliveryId;            
          self.dataSource.findById(requestedDeliveryId, self.currentDelivery);
      }
  });

  //Operations
  self.showDeliveries = function () 
       { self.nav.navigate({ view: 'deliveries' }) };
  self.showCustomers = function () 
       { self.nav.navigate({ view: 'customers' }) };

  self.showDelivery = function (delivery) {
      self.nav.navigate({ view: 'delivery', 
                    deliveryId: delivery.DeliveryId() })
  };

  self.nav.initialize({ linkToUrl: true });
}

Note that the onNavigate function uses the findById method on the upshot datasource that doesn't exist in the original beta release of ASP.NET MVC 4. Add the following javascript code to the upshot.knockout.extensions.js file. The highlighted line below is already present in the file so don't add it again.

(function (ko, upshot, undefined) {
    upshot.RemoteDataSource.prototype.findById = function (id, updateTarget) {
        function search() {
            var self = this;
            var foundEntity = 
                $.grep(ko.utils.unwrapObservable(self.getEntities()), 
                function (entity) {
                   return self.getEntityId(entity) === updateTarget._id;
                })[0];
            updateTarget(foundEntity);
        }

        if (!('_id' in updateTarget)) {
            // TODO: What is the provision to 'unbind' here?
            this.bind("refreshSuccess", search);
        }
        updateTarget._id = id;
        search.call(this);
    };

Also note that in the parent DeliveriesViewModel class, bufferChanges is put back to false in order to have immediate upshot synchronization with the service back-end

function DeliveriesViewModel() {
    // Private
    var self = this;
    var dataSourceOptions = {
        providerParameters: { url: "/api/DataService",
            operationName: "GetDeliveriesForToday"
        },
        entityType: "Delivery:#DeliveryTracker.Models",
        bufferChanges: false,
        mapping: Delivery
    };

    // Snip the rest of the code
    // ...
    // ...
}

The mobile layout

ASP.NET MVC can support mobile browsers by letting you create specific mobile pages using the ".mobile.cshtml" extension. In order to test these pages I installed this User-Agent Switcher for Chrome.

In the \Views\Shared folder, create two new files:

  • _SpaScripts.cshtml: partial view that groups the different javascript includes
  • _Layout.mobile.cshtml: layout page for mobile browsers

The _SpaScripts.cshtml: is quite simply

<script src="~/Scripts/jquery-1.6.4.min.js"
        type="text/javascript"></script>
<script src="~/Scripts/modernizr-2.0.6-development-only.js"
        type="text/javascript"></script>
<script src="~/Scripts/knockout-2.0.0.js"
        type="text/javascript"></script>
<script src="~/Scripts/arrayUtils.js"
        type="text/javascript"></script>
<script src="~/Scripts/upshot.min.js"
        type="text/javascript"></script>
<script src="~/Scripts/upshot.compat.knockout.js"
        type="text/javascript"></script>
<script src="~/Scripts/upshot.knockout.extensions.js"
        type="text/javascript"></script>
<script src="~/Scripts/native.history.js"
        type="text/javascript"></script>
<script src="~/Scripts/nav.js"
        type="text/javascript"></script>

The _Layout.mobile.cshtml: includes the _SpaScripts partial view and the navigation bar. The two list items in the navigation bar use data-binding to attach their functionality in a declarative way.

  • Their click events are linked to their respective show functions in the MobileDeliveriesViewModel
  • Their CSS style is adapted so they appear as active when their view is showing. You can find the Site.Mobile.css file in the code download at the end of this post.
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
    <link href="~/Content/Site.Mobile.css" rel="Stylesheet" type="text/css" />       
    <script src="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Scripts/js")">
    </script>
    <meta name="viewport" content="width=device-width" />

    @Html.Partial("_SpaScripts")

    <script src="~/Scripts/App/DeliveriesViewModel.js"
            type="text/javascript"></script>

  </head>
  <body>
    <nav class="bar">
        <ul>
          <li data-bind="click: showDeliveries, 
              css: { active: nav.params().view == 'deliveries' }">Deliveries</li>
          <li data-bind="click: showCustomers, 
              css: { active: nav.params().view == 'customers' }">Customers</li>
        </ul>
    </nav>

    @RenderBody()
  </body>
</html>

The mobile views

Now add a Index.mobile.cshtml to the \Views\Home folder. It's quite simple. When the DOM is ready a javascript function initializes the upshot library and initializes the knockout bindings to the MobileDeliveriesViewModel. The actual views are defined as partial views that are shown whenever their views are active.

Notice that the _DeliveryDetails view in Steven Sandersons example used the with: data-bind parameter. I couldn't get it to work so I encapsulated it within a parent div that checks the active view

@{
    ViewBag.Title = "Deliveries";
}

<script type="text/javascript">
    $(function () {
        upshot.metadata(@(Html.Metadata
                 <DeliveryTracker.Controllers.DataServiceController>()));
        ko.applyBindings( new MobileDeliveriesViewModel( ));
    });
</script>

<div data-bind="if: nav.params().view == 'deliveries'">
    @Html.Partial("_DeliveriesList")
</div>

<div data-bind="if: nav.params().view == 'customers'">
    @Html.Partial("_CustomersList")
</div>

<div data-bind="if: nav.params().view == 'delivery'">
    <div data-bind="with: currentDelivery">
        @Html.Partial("_DeliveryDetails")
</div>

The final items left to do are defining the partial views themselves. The only new functionality here is the $root pseudo-variable used by knockouts for-each data-binding which is used to bind the showDelivery method of the MobileDeliveriesViewModel to each item in the list

_CustomersList.cshtml

<div class="content">
    <label><input type="checkbox" data-bind="checked: excludeDelivered" />
              Only show undelivered items</label>

    <div data-bind="foreach: deliveriesForCustomer">
        <h4 data-bind="text: key.Name"></h4>
        <ol class="deliveries" data-bind="foreach: values">
            <li data-bind="text: Description, 
                           css: { updated: IsUpdated, delivered: IsDelivered }, 
                           click: $root.showDelivery"></li>
        </ol>
    </div>
</div>

_DeliveriesList.cshtml

<div class="content">
    <label><input data-bind="checked: excludeDelivered" type="checkbox" />
              Only show undelivered items</label>

    <ol class="deliveries" data-bind="foreach: deliveries">

        <li data-bind="css: { updated: IsUpdated, delivered: IsDelivered },
                                        click: $root.showDelivery">
            <span data-bind="text: Description"></span>
            <span class="details" data-bind="text: Customer().Name"></span>
        </li>

    </ol>
</div>

_DeliveryDetails.cshtml

<div class="title bar">
    <button data-bind="click: History.back">&lt; Back</button>
    <h1 data-bind="text: Description"></h1>
</div>

<div class="content">
    <p>Delivery #<strong data-bind="text: DeliveryId"></strong></p>

    <div class="callout" data-bind="with: Customer">
        <h1>Customer</h1>

        <label>Name</label>
        <strong data-bind="text: Name"></strong>
        
        <label>Address</label>
        <strong data-bind="text: Address"></strong>
    </div>
    
    <label class="checkbox" data-bind="css: { delivered: IsDelivered }">
        <input type="checkbox" data-bind="checked: IsDelivered" /> Delivered
    </label>
</div>

Following navigation map shows the mobile application in action

  • The 'deliveries' screen with the list of deliveries. Clicking a delivery navigates to the 'delivery' screen
  • The 'customers' screen with the list of deliveries grouped by customer. Clicking a delivery navigates to the 'delivery' screen. In the URL you can see the 'view=customer' parameter.
  • The 'delivery' screen containing the delivery details per item. In the URL you can see the 'view' and the 'deliveryId' parameters. Clicking 'Back' navigates back to the previous page.
  • All of these views exist on the same webpage but by changing the URL, the back button and bookmarking functions as you would expect

Download the source code

You can download the source code (Visual Studio 2010 solution) from my Skydrive.

Wednesday, March 7, 2012

Building Single Page Apps with ASP.NET MVC4 - Part 2 - Advanced Desktop Application

This is the second article in a series about building single page applications using ASP.NET MVC4. I assume that you have read the first part.
  1. Single Page Applications - Part 1 - Basic Desktop application
  2. Single Page Applications - Part 2 - Advanced Desktop Application
  3. Single Page Applications - Part 3 - Basic Mobile Application
  4. Single Page Applications - Part 4 - Sorting, Filtering and Manipulation data with upshot.js
  5. Single Page Applications - Part 5 - With MVC4 RC

In part 1 I recreate the first part of a demo by Steven Sanderson that shows a list of deliveries on screen, allows a user to mark an item as delivered and have the results immediately sent back to the server. In this second part the application will also show the deliveries grouped by customer and uses "Save All" and "Revert All" buttons so that the user can decide when to update the back-end.

Group by Customer

In order to group deliveries by customer, you'll need to a bit of javascript code that can go over the observable 'deliveries' array and group them together based on the referenced customer. This grouped data needs to be observable too. Steven has released the following bit of javascript called arrayUtils.js in order to achieve this:



/// <reference path="knockout.debug.js" />

(function () {
    function firstWhere(array, condition) {
        for (var i = 0; i < array.length; i++)
            if (condition(array[i]))
                return array[i];
    }

    ko.observableArray.fn.groupBy = function (keySelector) {
        if (typeof keySelector === "string") {
            var key = keySelector;
            keySelector = function (x) 
                          { return ko.utils.unwrapObservable(x[key]) };
        }
        var observableArray = this;

        return ko.computed(function () {
            var groups = [], array = observableArray();
            for (var i = 0; i < array.length; i++) {
                var item = array[i],
                existingGroup = firstWhere(groups, function (g) 
                                { return g.key === keySelector(item) });
                if (existingGroup)
                    existingGroup.values.push(item);
                else
                    groups.push({ key: keySelector(item), values: [item] });
            }
            return groups;
        })
    }
})();
You can now add a new datasource to the DeliveriesViewModel.js like this:
    self.deliveries = self.dataSource.getEntities();
    self.deliveriesForCustomer = self.deliveries.groupBy("Customer");
To show this new information on screen, add following code to index.cshtml. The groupBy operator has put every customer object on the "key" parameter and all his deliveries on the "values" parameter.
    <h3>Customers</h3>
    <ul data-bind="foreach: deliveriesForCustomer">
        <li>
            <div>Name: <strong data-bind="text: key.Name"></strong></div>
            <ul data-bind="foreach: values">
                <li data-bind="text: Description, 
                                css: { highlight: IsDelivered }">                
                </li>
            </ul>
        </li>    
    </ul>

If you would run the application now you will notice that knockout.js is keeping the values is the deliveries list and the customers list in sync.

Save, Revert, Exclude if delivered

Upshot can be configured to NOT synchronize the changes to the backend, meaning the user will have to click a "Save" button when he wants to submit. There is also the possibility to undo the accumulated changes or to put a filter on the datasource. In order to enable above functionality, make the following changes to the DeliveriesViewModel.js
  • Set bufferChanges to true so that the upshot datasource will keep the changes in memory and not sync them with the back-end
  • Create a self.localDataSource that we can use for client-side operations like filtering the data
  • Create a self.excludeDelivered variable to keep track of the value of the checkbox saying the user wants to exclude already delivered items from the list
  • Create the self.saveAll and self.revertAll function to commit or revert the changes on the upshot datasource
  • Subscribe a function to the self.excludeDelivered observable that gets called everytime the value changes. Inside this function a new filter rule is created which is then applied to the local data source
/// <reference path="_references.js" />

function DeliveriesViewModel() {
    // Private
    var self = this;
    var dataSourceOptions = {
        providerParameters: { url: "/api/DataService",
                    operationName: "GetDeliveriesForToday" },
        entityType: "Delivery:#DeliveryTracker.Models",
        bufferChanges: true,
        mapping : Delivery
    };

    // Public Properties
    self.dataSource = new upshot.RemoteDataSource(dataSourceOptions).refresh();
    self.localDataSource = upshot.LocalDataSource({ source: self.dataSource,
                                               autoRefresh: true });

    self.deliveries = self.localDataSource.getEntities();
    self.deliveriesForCustomer = self.deliveries.groupBy("Customer");
    self.excludeDelivered = ko.observable(false);

    // Operations
    self.saveAll = function () { self.dataSource.commitChanges() }
    self.revertAll = function () { self.dataSource.revertChanges() }

    // Delegates
    self.excludeDelivered.subscribe(function (shouldExcludeDelivered) {
        var filterRule = shouldExcludeDelivered 
            ? { property: "IsDelivered", operation: "==", value: false }
            : null;
        self.localDataSource.setFilter(filterRule);
        self.localDataSource.refresh();
    });
}

Include the new arrayUtils.js in the Index.cshtml file

<script src="~/Scripts/arrayUtils.js"
        type="text/javascript"></script>
<script src="~/Scripts/App/DeliveriesViewModel.js"
        type="text/javascript"></script>
To take advantage of the functionalities you can bind the view to the functions that have been put in place in the DeliveriesViewModel
  • Added two buttons of which knockout binds the click event to the appropriate functions in the DeliveriesViewModel
  • The "Exclude Delivered items" checkbox bound to the 'excludeDelivered' property in the viewmodel
  • The 'delivered' CSS class is bound to the existing 'IsDelivered' property which was foreseen on the view model. The 'updated' CSS class however is bound to the 'IsUpdated' property that comes built-in with the observable datasource
<div>
    <h3>Deliveries</h3>

    <button data-bind="click: saveAll">Save All</button>
    <button data-bind="click: revertAll">Revert All</button>

    <label>
        <input data-bind="checked: excludeDelivered" type="checkbox" />
         Exclude delivered items</label>

    <ol data-bind="foreach: deliveries">
        <li data-bind="css: { delivered: IsDelivered, 
                                        updated: IsUpdated}">
            <strong data-bind="text: Description"></strong>
            is for <em data-bind="text: Customer().Name"></em>
            <label><input data-bind="checked: IsDelivered" 
                  type="checkbox"/>Delivered</label>
        </li>
    </ol>

    <h3>Customers</h3>
    <ul data-bind="foreach: deliveriesForCustomer">
        <li>
            <div>Name: <strong data-bind="text: key.Name"></strong>
            </div>
            <ul data-bind="foreach: values">
                <li data-bind="text: Description, 
                    css: { delivered: IsDelivered,
                             updated: IsUpdated}">                
                </li>
            </ul>
        </li>    
    </ul>
</div>
I've defined these new styles in Site.css
.delivered
{
    text-decoration: line-through;
    color: #008000;
}

.updated
{
    background-color: #FFFF00;
}

If you now mark items as delivered, they will get the 'delivered' AND 'updated' styles in both lists. These are nicely kept in sync by upshot. When the user clicks the "SaveAll" button, all changes will be submitted to the server and the 'updated' style will disappear. The "RevertAll" button undoes all the changes. Selecting "Exclude Delivered Items" will remove the delivered items from the shared datasource so they won't show up in either list.

Download the source code

You can download the code (Visual Studio 2010 project file) from my SkyDrive