Partager via


Connecting to WCF RIA Services in a Windows 8 Metro Style App using Upshot.js and Knockout.js

Overview

After messing around with KnockoutJS inside of Metro Style Apps I decided to dive a little deeper and see what Single Page Applications (particularly Upshot.js) could offer.  I’ve gotten asked by more than a few developers how best to connect to their existing WCF RIA Services inside of Metro Style Apps.  The approach I took here is one possible solution to help get your started.

UpshotOverview

 

For those not familiar with Upshot it is a JavaScript Library that allows you to connect to WCF RIA Services.  It is by the same great wizards who wrote ASP.NET MVC4 Single Page Applications. and included already in Single Page App templates! 

I also came across two really great posts you should check out that helped me get my head around things:

Upshot.js & Knockout.js: The HTML5 Client for WCF RIA Services

Building Single Page Apps with ASP.NET MVC4 - Part 1 - Basic Desktop Application

If you just want to grab the MVC4 and Windows 8 Metro Style App source code you can download them here:

DownloadExample

 

Setting up the MVC 4 Environment

In order to get the MVC4 Single Page Application Templates I downloaded and installed Visual Studio 2011 Beta Ultimate (currently freely available here).  I am running everything local: MVC4 Website is using IIS Express and the data is stored in SQL Server 2008 R2 Express( the one that comes with the Web Platform Installer).  The code that I used was based of a great sample Bart Jolling wrote on his blog here

The example is a simple Deliverytracker SIngle Page Application that looks like this:

SPA-MVC4 

To  keep things simple I am running everything local with integrated security on IIS Express and SQL Server Express.

 

Also take note of our DomainModel as we will need to manually set up MetaData for this later.

 public class Customer
 {
     public int CustomerId { get; set; }
     public string Name { get; set; }
     public string Address { get; set; }
 }
  
 public class Delivery
 {
     public int DeliveryId { get; set; }
     public virtual int CustomerId { get; set; }
     public virtual Customer Customer { get; set; }
  
     public string Description { get; set; }
     public bool IsDelivered { get; set; }
 }

 

Setting up the Metro Style App to use Upshot.js

I then created a new JavaScript based Metro Style App like usual and selected the Tools – > Library Package Manager – > Manage NuGet Packages for Solution menu and searched for UpShot.

GrabUpshot

This will bring down all the required scripts you need for using Upshot.js in your application.

InstalledScripts

Because the package installer assumes we are inside of an MVC application it will write everything into a new /scripts folder.  For simplicity sake I removed the /scripts folder and copied all of the JavaScript files into our existing /js folder.

 

Declaration and Initialization

We now reference these new JavaScript Libraries like usual inside of our default.html.

 <script type="text/javascript" src="js/jquery-1.6.4.js"></script>
 <script type="text/javascript" src="js/knockout.debug.js"></script>
 <script type="text/javascript" src="js/knockout.js"></script>
 <script type="text/javascript" src="js/DeliveriesViewModel.js"></script>
 <script type="text/javascript" src="js/upshot.js"></script>
 <script type="text/javascript" src="js/upshot.compat.knockout.js"></script>
 <script type="text/javascript" src="js/upshot.knockout.extensions.js"></script>
 <script type="text/javascript" src="js/arrayUtils.js"></script>

There are two additional scripts here arrayUtils.js and DeliveriesViewModel.js that I copied over from the MVC4 Single Page Application DeliveryTracker example  mentioned previously.  arrayUtils is a helper function we can leave as is and DeliveriesViewModel will be how we wire up to our service. 

The next step was to take the code from our MVC4 app’s Home View located in /Views/Home/Index.cshtml and move it into our Metro Style App.

 <section>
 <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>
 </section>

 

All of this gets done inside our default.html:

 <!DOCTYPE html>
 <html>
 <head>
     <meta charset="utf-8">
     <title>UpshotWin8</title>
  
     <!-- WinJS references -->
     <link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet">
     <script src="//Microsoft.WinJS.0.6/js/base.js"></script>
  1:  
  2:     <script src="//Microsoft.WinJS.0.6/js/ui.js">
  1: </script>
  2:  
  3:     <script type="text/javascript" src="js/jquery-1.6.4.js">
  1: </script>
  2:     <script type="text/javascript" src="js/knockout.debug.js">
  1: </script>
  2:     <script type="text/javascript" src="js/knockout.js">
  1: </script>
  2:     <script type="text/javascript" src="js/DeliveriesViewModel.js">
  1: </script>
  2:     <script type="text/javascript" src="js/upshot.js">
  1: </script>
  2:     <script type="text/javascript" src="js/upshot.compat.knockout.js">
  1: </script>
  2:     <script type="text/javascript" src="js/upshot.knockout.extensions.js">
  1: </script>
  2:     <script type="text/javascript" src="js/arrayUtils.js">
  1: </script>
  2:  
  3:  
  4:     <!-- UpshotWin8 references -->
  5:     <link href="/css/default.css" rel="stylesheet">
  6:     <script src="/js/default.js">
 </script>
  
  
 </head>
 <body>
  
 <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>
  
 </body>
 </html>

 

Once we have our view code wired up we now need to call out to the service and databind everything.  Just like my previous KnockoutJS examples I wire up everything after the DomContentLoaded Event has fired using a custom function called initialize.

 document.addEventListener("DOMContentLoaded", initialize);

Initialize will then tell our app about the fields returned by our Domain Service.  In order to do this we need to call the upshot.metadata function and map values manually based on their original DomainModel source types.  The basic formatting used here is Classname#Namespace.  Once you get your head around that it’s pretty easy to map everything (although laborious).  I also set the key to be based of DeliveryID.  

After our mapping are set we’ll tell KnockoutJS to bind everything using the provided DeliveriesViewModel function.

 function initialize() {
       
  
     upshot.metadata({
         "Delivery:#DeliveryTracker.Models": {
             "key": ["DeliveryId"],
             "fields": {
                 "DeliveryId": { "type": "Int32:#System" },
                 "CustomerId": { "type": "Int32:#System" },
                 "Customer": { "type": "Customer#DeliveryTrack.Models" },
                 "Description": { "type": "String:#System" },
                 "isDelivered": { "type": "Int32:#System" }
             }
         }
     });
  
     ko.applyBindings( new DeliveriesViewModel( ));
  
 }

 

The last step now is to edit our DeliveriesViewModel.js file with the location of our Domain Service.  This will be different for everyone but on my local machine the service runs at https://localhost:61907//api/DataService.

 function DeliveriesViewModel() {
     // Private
  
     var dataSourceOptions = {
         providerParameters: {
             url: "https://localhost:61907//api/DataService",
             operationName: "GetDeliveriesForToday"
         },
         entityType: "Delivery:#DeliveryTracker.Models",
         bufferChanges: true,
         mapping: Delivery
     };
  
     // Public Properties
     this.dataSource = new upshot.RemoteDataSource(dataSourceOptions).refresh();
     this.localDataSource = upshot.LocalDataSource({ source: this.dataSource,
         autoRefresh: true
     });
  
     this.deliveries = this.localDataSource.getEntities();
     this.deliveriesForCustomer = this.deliveries.groupBy("Customer");
     this.excludeDelivered = ko.observable(false);
  
     // Operations
     this.saveAll = function () { this.dataSource.commitChanges() }
     this.revertAll = function () { this.dataSource.revertChanges() }
  
     // Delegates
     this.excludeDelivered.subscribe(function (shouldExcludeDelivered) {
         var filterRule = shouldExcludeDelivered
             ? { property: "IsDelivered", operation: "==", value: false }
             : null;
         this.localDataSource.setFilter(filterRule);
         this.localDataSource.refresh();
     });
 }
  
 function Customer (data) {
  
     this.CustomerId = ko.observable(data.CustomerId);
     this.Name = ko.observable(data.Name);
     this.Address = ko.observable(data.Address);
     upshot.addEntityProperties(this, "Customer:#DeliveryTracker.Models");
 }
  
 function Delivery (data) {
   
  
     this.DeliveryId = ko.observable(data.DeliveryId);
     this.CustomerId = ko.observable(data.CustomerId);
     this.Customer = ko.observable(data.Customer);
     this.Description = ko.observable(data.Description);
     this.IsDelivered = ko.observable(data.IsDelivered);
     upshot.addEntityProperties(this, "Delivery:#DeliveryTracker.Models");
 }

 

Other than the service location I did not need to modify the function in any way from the original MVC4 DeliveryTracker example.

We now have the Metro Style App binding to the same Domain Service and being fully interactive. 

RunningMetroApp

 

 

Conclusion

Obviously we would need to style the application to make it feel like a native Metro Style App but the hard plumbing work has been done.  We were able to keep a majority of the MVC4 code, from both the views and the model, to get us started with our Windows 8 Metro Style App! 

 

If you are currently working on a Windows 8 app I would love to hear about it.  You may also want to check out my previous Windows 8 Metro Style Development Tips:

Comments

  • Anonymous
    May 03, 2012
    The comment has been removed
  • Anonymous
    May 03, 2012
    The comment has been removed