Sunday, April 1, 2012

Upshot.js & knockout.js: The HTML5 client for WCF RIA services

As Microsoft is leaving the Silverlight track and more and more focusing on HTML5 for cross browser support, solutions are coming for several existing frameworks. One of the things I’ve been looking at is the possibility to reuse your existing RIA services ,who you currently use for your Silverlight application, and port them to HTML5 enabled website.

The HTML client for ria services started as an jQuery plugin called Ria.js. Currently this project is hosted into the ASP.NET Single Page Application. This is a new project template for building single page applications. The advantage of these kind of application is that they run completely in the browser, this way it’s pretty easy to enable your application to be used offline.

The JS client framework used for communicating with the server is Upshot.js. This framework provides a rich context for the object used on the client side, this includes change tracking, paging, sorting, … More information of this subject can be found on the Denver Developers blog. If you prefer watching a live demo, Steve Sanderson gave one at TechDays Netherlands.

While searching on the net for some more information, I noticed that the most examples focus on the use of Web API for communication with the server. Next to the standard Web API provider for upshot, there is also support for RIA and OData. Since my post is handling RIA services, I‘ll be handling the riaDataProvider.

Building a live demo

Perquisite:

So lets get started by creating a new MVC4 project:

Create SPAWithRiaServices project

If we press the OK button, we can choose which MVC4 project template we want to use. In our case we choose for the Single Page Application.

Create SPAWithRiaServices project step 2

This template includes already some models, controls and views, but when we open up the scripts folder, we will see the script references for upshot.js, knockout.js, … Everything we need for building an HTML5 application with a rich context. But these frameworks evolve fast and thank god we have a thing called Nuget so we can easily update to the latest version. So this will be the next step in my tutorial, updating to the latest version of the single page application. Search for SinglePageAppliction in your Nuget packet management explorer or type the following in your package manager explorer:

Install-Package SinglePageApplication.CSharp



Once this is done, we need to add the reference to the ServiceModel so we can use the domainService class of the RIA services. The following references need to be added (note that these references come from the latest version of the WCF Ria Services SDK V1,  C:\Program Files (x86)\Microsoft SDKs\RIA Services\v1.0\Libraries\Server):





System.ServiceModel.DomainServices.Hosting
System.ServiceModel.DomainServices.Server



And one reference from the SP2 of the WCF Ria Services SDK V1, C:\Program Files (x86)\Microsoft SDKs\RIA Services\v1.0\Toolkit\Libraries\Server\SP2\





Microsoft.ServiceModel.DomainServices.Hosting



After adding the references, we need to configure our DomainServices. First thing we need to do is adding a new configuration section for the DomainService






<configSections>
  <sectionGroup name="system.serviceModel">
    <section name="domainServices" 
type="System.ServiceModel.DomainServices.Hosting.DomainServicesSection, 
      System.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, 
      Culture=neutral, PublicKeyToken=31bf3856ad364e35" 
      allowDefinition="MachineToApplication" requirePermission="false" />
  </sectionGroup>
</configSections>



Next we add a new httpModule for the DomainService to the system.web section






<system.web>
  <httpModules>
    <add name="DomainServiceModule" 
type="System.ServiceModel.DomainServices.Hosting.DomainServiceHttpModule, 
      System.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, 
      Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  </httpModules>
</system.web>



In the system.webServer section, we add a new module for the DomainService






<system.webServer>
  <validation validateIntegratedModeConfiguration="false" />
  <modules runAllManagedModulesForAllRequests="true">
    <add name="DomainServiceModule" preCondition="managedHandler"
 type="System.ServiceModel.DomainServices.Hosting.DomainServiceHttpModule, 
       System.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, 
       Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  </modules>
</system.webServer> 



As last we add the following system.serviceModel config section. Most important thing here is that we add a JSON endpoint, and on this endpoint we add the attribute transmitMetadata=”true” so the metadata is send to our HTML client.






<system.serviceModel>
  <domainServices>
    <endpoints>
      <add name="JSON" 
 type="Microsoft.ServiceModel.DomainServices.Hosting.JsonEndpointFactory, 
       Microsoft.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, 
       Culture=neutral, PublicKeyToken=31bf3856ad364e35" 
       transmitMetadata="true" />
    </endpoints>
  </domainServices>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
        multipleSiteBindingsEnabled="true" />
</system.serviceModel>





Once all the references and configuration sections are added, we can start to code. The first thing we do is adding a new class and let it derive from DomainService.






using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.DomainServices.Hosting;
using System.ServiceModel.DomainServices.Server;
using SPAWithRiaServices.Models;
 
namespace SPAWithRiaServices.Services
{
    /// <summary>
    /// Domain Service responsible for todo items.
    /// </summary>
    [EnableClientAccess]
    public class TodoItemDomainService : DomainService
    {
        [Query(IsDefault = true)]
        public IQueryable<TodoItem> GetTodoItems()
        {
            IList<TodoItem> todoItems = new List<TodoItem>();
 
            todoItems.Add(new TodoItem() 
                { TodoItemId = 1, Title = "Todo item 1", IsDone = false });
            todoItems.Add(new TodoItem() 
                { TodoItemId = 2, Title = "Todo item 2", IsDone = false });
            todoItems.Add(new TodoItem() 
                { TodoItemId = 3, Title = "Todo item 3", IsDone = false });
            todoItems.Add(new TodoItem() 
                { TodoItemId = 4, Title = "Todo item 4", IsDone = false });
 
            return todoItems.AsQueryable<TodoItem>();
        }
    }
}




The TodoItem Class looks as follows:






using System.ComponentModel.DataAnnotations;
 
namespace SPAWithRiaServices.Models
{
    public class TodoItem
    {
        [Key]
        public int TodoItemId { get; set; }
        [Required]
        public string Title { get; set; }
        public bool IsDone { get; set; }
    }
}



Now we can go to edit the views. The first view we need to change is the _Layout.cshtml in the shared folder. In here we delete the following line:






<script src="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Scripts/js")"></script>



And add the following references instead:






<script src="~/Scripts/jquery-1.6.2.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.debug.js" 
        type="text/javascript"></script>
<script src="~/Scripts/upshot.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>


In the index.cshtml in the home folder, we add the following:



The configuration for using upshot






<script type='text/javascript'>
    upshot.dataSources = upshot.dataSources || {};
    
    upshot.dataSources.GetTodoItems = upshot.RemoteDataSource({
        providerParameters: { 
            url: "/SPAWithRiaServices-Services-TodoItemDomainService.svc", 
            operationName: "GetTodoItems" 
        },
        provider: upshot.riaDataProvider,
        bufferChanges: true,
        dataContext: undefined,
        mapping: {}
    });
</script>



The knockout view






<ol data-bind="foreach: todoItems">
    <li><strong data-bind="text: Title"></strong>
        <label>
            <input data-bind="checked: IsDone" type="checkbox" />
            Done
        </label>
    </li>
</ol>



And as last the ViewModel definition






<script type="text/javascript">
    function TodoItemViewModel() {
        // Data
        var self = this;
        self.dataSource = upshot.dataSources.GetTodoItems.refresh();
        self.localDataSource = upshot.LocalDataSource({ 
                                    source: self.dataSource
                                  , autoRefresh: true });
        self.todoItems = self.localDataSource.getEntities();
    }
 
    $(function () {
        ko.applyBindings(new TodoItemViewModel());
    });
</script>



When you run the application now, you should see the todo items appear on your screen with a little delay.



Conclusion



In your HTML applications you can take advantage of your existing RIA services with a minimum of effort. For now the possibilities are limited, but I think in the future we will be able to use all features as they are present in SL. By adding the transmitMetadata attribute to our JSON endpoint, it isn’t necessary to define the model again on the client side.

30 comments:

  1. The demo application can be found here: http://bit.ly/Hmyp2c

    ReplyDelete
  2. Added an extra link to the WCF Ria Services Toolkit. This one needs to be installed if you want to reference to Microsoft.ServiceModel.DomainServices.Hosting

    ReplyDelete
  3. love mvvm, love wcf, love html 5 what more do ya need right.
    nice tutorial kristof

    ReplyDelete
  4. This is very educational content and written well for a change. It's nice to see that some people still understand how to write a quality post! 24 hour truck tire repair

    ReplyDelete
  5. Thanks a lot very much for the high quality and results-oriented help. I won’t think twice to endorse your blog post to anybody who wants and needs support about this area.
    java training in bangalore

    java training in bangalore

    ReplyDelete
  6. Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained! Productized service software

    ReplyDelete
  7. Very interesting blog which helps me to get the in depth knowledge about the technology, Thanks for sharing such a nice blog...
    No.1 Summer Training Courses in Porur | Best Summer Courses for Hardware Networking in Chennai

    ReplyDelete

  8. Post is very informative… It helped me with great information so I really believe you will do much better in the future.
    C,C++ Summer Course training Institute in Chennai|C,C++ Summer Course training Institute in Velachery

    ReplyDelete
  9. I'm very glad when read your article. It's easy to understand and very useful for newbie as me... Hardware and Networking Certifications in Chennai | No.1 Networking in Perungudi

    ReplyDelete
  10. Thank you for Sharing. Brave Technologies is a leading low cost per software solution providers in chennai.
    CompTIA A+ Certifications Center in Chennai | A+ Exams in Perungudi

    ReplyDelete
  11. Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing.
    Cisco Certifications Exam Center in Chennai | Best Cisco Course in Thiruvanmiyur

    ReplyDelete
  12. I have read your blog its very attractive and impressive. I like it your blog.
    Comptia Network+ Certification Courses in Chennai | Best N+ Courses in Tambaram

    ReplyDelete
  13. Pretty good list. My personal guideline is just to respond in a genuine way to what interests me. thanks for sharing...Android Certifications Exam Center in Chennai | Best Android Exam in Mandaveli

    ReplyDelete
  14. Excellent post!!!. The strategy you have posted in this technology helped me to get into the next level and had lot of information in it.
    ISTQB Certifications Course in Chennai | QA Testing in Medavakkam

    ReplyDelete
  15. I learn new information from your article , you are doing a great job . Keep it up
    No.1 ISTQB Certifications Exam Course in Chennai | Testing in Thiruvanmiyur

    ReplyDelete
  16. Thanks for this blog. Very good knowledge and very good information. The simplest method to do this process....
    Android Certifications Exam Training in Chennai | Android Course in Adyar

    ReplyDelete
  17. Impressive blog with lovely information. really very useful article for us thanks for sharing such a wonderful blog...
    Python Certification Exam Coaching in Chennai | Best Python Training in T.Nagar

    ReplyDelete
  18. I too always learn something new from your post Great post….thanks for sharing this profitable data..
    CompTIA Network Plus Certifications Exam Training in Chennai | Network Plus in Adambakkam

    ReplyDelete
  19. Excellent post. I have read your blog it's very interesting and informative.Thanks for sharing such nice article, keep on up dating such good articles.
    Cisco CCNA Certification Course in Chennai | Excellent Cisco CCNA Course in Tambaram

    ReplyDelete
  20. Thanks for sharing the information on the importance of content as it plays a vital role.
    ISTQB Certified Tester Exam Center in Chennai | QA Testing in Alandur

    ReplyDelete
  21. wow..Very interesting and happy to visit this blog. the trip, it may be so thrill.
    CorelDraw Training Courses in Chennai | No.1 Multimedia Training in Guindy

    ReplyDelete
  22. Thanks for sharing this unique and informative content which provided me the required information.
    Cisco CCNP Certification Center in Chennai | CCNA Training in Velachery | No.1 CCNP Course in Guindy

    ReplyDelete
  23. Nice..You have clearly explained about it ...Its very useful for me to know about new things..Keep on blogging..
    Dot Net Project Center in Chennai | Dot Net Training in Guindy

    ReplyDelete
  24. Great article..really nice to read, very informative blog thanks for sharing..
    Android Project Center in Chennai | No.1 Android Training in Velachery

    ReplyDelete
  25. I'm very glad when read your article. It's easy to understand and very useful for newbie as me...
    VLSI Project Center Training in Chennai | Best VLSI Project Course in Alandur

    ReplyDelete