Geeks With Blogs

News Ashraful Alam Joy

Create Your Badge

Ashraful Alam is a Software Architect, who has 8 years of professional experience in Software Development industry. This Bangladeshi national is involved with project management and development of several US based software projects from his country. Already he has managed and developed several software projects, which are being used by several users of different countries, such as USA, Canada, Australia, and Bangladesh. While developing and managing a team, he contains and maintains a set of well defined engineering practices developed by him and other online developer communities.

Due to his willingness to give effort to improve and share better software development practices, Ashraf has been awarded as “Most Valuable Professional” (MVP) in ASP.NET category by Microsoft since year 2007 multiple times, which is a rare honor and prestigious reorganization among the developers around the world.

Check his portfolio to know more about him and his works.


.NETTER Characters... Every part of your life is best, if you can know yourself and thus create your life like an artist!

Ajax enabled data centric applications are getting popular day by day in web development space. While these type of web applications provide rich user experience, building a robust and powerful application quickly is a great challenge for developers. Fortunately Microsoft has started providing great frameworks, plug-ins and APIs to facilitate this process.

Last week Microsoft announced a new version of java-script API “datajs”, which is intended to help web developers to build data centric AJAX applications quickly, along with utilizing modern browsers features (such as HTML5 local storage, IndexDB etc) and protocols (such as oData). Datajs is designed to be small, fast and easy to use.

While datajs includes lots of cool features, today in this post, I will have a very basic introductory quick start so that any developer can have an idea how datajs can be implemented in different application architecture. Checkout last week’s MIX session video to learn few cool features available in datajs.

Download the full quick start sample from here.

Invoking Cross-Domain Service

Netflix has provided an excellent oData API to enable developers to experiment with their data hosted in their infrastructure. The code below, uses NetFlix service and datajs API to show movie data. The cool thing is you really don’t need to build any web or data service to test your app.

<html>
<head>
    <script type="text/javascript" src="datajs-0.0.3.min.js"></script>
    <script type="text/javascript">
        var url = "http://odata.netflix.com/Catalog/Titles";
 
        OData.defaultHttpClient.enableJsonpCallback = true;
 
        OData.read(
                url,
                function (data, request) {
                    var html = "";
                    for (var i = 0; i < data.results.length; i++) {
                        html += "<div>" + data.results[i].Name + "</div>";
                    }
                    document.getElementById("Movies").innerHTML = html;
                },
                function (err) {
                    alert("Error occurred ");
                });
 
    </script>
    <title>Movies - dataJS + Netflix</title>
</head>
<body>
    <div id="Movies">
    </div>
</body>
</html>

 

Invoking WCF Data Service

WCF Data Service is a part of Windows Communication Foundation that exposes REST style data. You can use Entity Framework to build WCF Data Service in literally few seconds.

WCF Data Service code:

    public class WCF_Data_Service : DataService<DatabaseContext>
    {
        public static void InitializeService(DataServiceConfiguration config)
        {
            config.SetEntitySetAccessRule("*", EntitySetRights.All);
            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
        }
    }

 

and the UI code:

 

<html>
<head>
    <script type="text/javascript" src="datajs-0.0.3.min.js"></script>
    <script type="text/javascript">
        var url = "../App_Service/WCF-Data-Service.svc/Employees";
        OData.read(
                url,
                function (data, request) {
                    var html = "";
                    for (var i = 0; i < data.results.length; i++) {
                        html += "<div>" + data.results[i].FirstName + " " + data.results[i].LastName + "</div>";
                    }
                    document.getElementById("dvEmployees").innerHTML = html;
                },
                function (err) {
                    alert("Error occurred ");
                });
    </script>
    <title>Employees - dataJS + WCF Data Service + oData</title>
</head>
<body>
    <div id="dvEmployees">
    </div>
</body>
</html>

 

Invoking WCF Service

While WCF Data Service enables you to build REST style services pretty quickly, one problem with this approach is, it’s very hard to implement business logic during CRUD operation. One solution in this regard, is to create Ajax Enabled WCF Service, where you will invoke a web method, that contains your business logic.

 

[ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class WCF_Business_Service
    {
        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]
        public List<Customer> GetAllCustomers()
        {
            List<Customer> lst = new List<Customer>();
            
            //business logic goes here
 
            return lst;
        }
 
    }

 

For the WCF Service contract, as shown above, you will use datajs, as shown below:

 

<html>
<head>
    <script type="text/javascript" src="datajs-0.0.3.min.js"></script>
    <script type="text/javascript">
        var url = "../App_Service/WCF-Business-Service.svc/GetAllCustomers";
        OData.read(
                url,
                function (data, request) {
                    var html = "";
                    for (var i = 0; i < data.results.length; i++) {
                        html += "<div>" + data.results[i].FirstName + " " + data.results[i].LastName + "</div>";
                    }
                    document.getElementById("dvCustomers").innerHTML = html;
                },
                function (err) {
                    alert("Error occurred" + err.message);
                });
       
    </script>
    <title>Employees - dataJS + WCF Service (Ajax Enabled) + oData</title>
</head>
<body>
    <div id="dvCustomers">
    </div>
</body>
</html>

 

Lets Make it Look Better!

So far the samples we have seen, contains very plain markup in HTML. The sample below shows how we can use in ASP.NET, along with jQuery Template plug-in to make it look better!

<%@ Page Title="" Language="C#" MasterPageFile="~/App_Resources/default.master" AutoEventWireup="true" %>
 
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContentPlaceHolder" runat="Server">
    <script type='text/javascript' src='<%# ResolveUrl ("~/App_Resources/client-scripts/framework/jquery-tmpl.js") %>'></script>
    <script type='text/javascript' src='<%# ResolveUrl ("~/datajs-oData/datajs-0.0.3.min.js") %>'></script>
    <script type="text/javascript">
        var url = "../App_Service/WCF-Data-Service.svc/Employees";
        OData.read(
                url,
                function (data, request) {
                    $("#employeeListingTemplateContainer").empty();
                    var returnedEmployeeCollection = data.results;
                    $("#employeeListingTemplate").tmpl({ employeeCollection: returnedEmployeeCollection }).appendTo("#employeeListingTemplateContainer");
 
                },
                function (err) {
                    alert("Error occurred ");
                });
    </script>
    <!-- Employee Listing Template -->
    <script id="employeeListingTemplate" type="text/html">
        <tbody>
            <tr class="HeaderStyle">
                <td>
                    <a>
                        First Name</a>
                </td>
                <td>
                    <a>
                        Last Name</a>
                </td>
                <td>
                    <a>
                        Country</a>
                </td>
               </tr>
            {{each employeeCollection}}
                <tr class="RowStyle">
                    <td>
                        ${FirstName}
                    </td>
                    <td>
                        ${LastName}
                    </td>
                    <td>
                        ${Country}
                    </td>
                </tr>
            {{/each}}
        </tbody>
    </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="BodyContentPlaceholder" runat="Server">
    <h1 class="title-regular">
        Employees</h1>
    <p>
        In this page you will be able to view the list of all employess.
    </p>
    <div>
        <table id="employeeListingTemplateContainer" class="GridView">
            <%-- Employee listing table data will be placed here--%>
        </table>
    </div>
</asp:Content>

 

Here goes the UI:

 

image

Download the entire quick start code sample from here.

Happy coding!

Posted on Tuesday, April 19, 2011 6:36 AM | Back to top


Comments on this post: Microsoft datajs API: A 5 Minutes Quick Start

# re: Microsoft datajs API: A 5 Minutes Quick Start
Requesting Gravatar...
nice post.it helps :)
Left by Monjurul Habib on Apr 19, 2011 12:17 PM

# re: Microsoft datajs API: A 5 Minutes Quick Start
Requesting Gravatar...
Awesome!!! Technology is running so fast.
Left by khabir on Apr 19, 2011 3:40 PM

Your comment:
 (will show your gravatar)


Copyright © Ashraf Alam | Powered by: GeeksWithBlogs.net | Join free