Consuming JSON in Windows 8 Metro style Application using WinJS

In this post I will discuss way of consuming JSON service in Windows 8 metro style application. In this post,

  • Metro app is created using HTML 5 and Service is being consumed using WinJS
  • Service is created service using WCF and REST is on service using webHttpBinding.

Since creating simple REST Service returning JSON is not main focus of this post, so I will show creation WCF REST Service returning JSON in later part of this post.

Consuming JSON using WinJS

We need to consume service in HTML 5 Metro application. Very first let us design HTML page

default.html


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>HelloWorldJavaScript</title>
<!-- WinJS references -->
<link rel="stylesheet" href="/winjs/css/ui-dark.css" />
<script src="/winjs/js/base.js"></script>
<script src="/winjs/js/wwaapp.js"></script>
<!-- HelloWorldJavaScript references -->
<link rel="stylesheet" href="/css/default.css" />
<script src="/js/default.js"></script>
</head>
<body>
<label >First Number</label>
<input id="TextboxFirstNumber" type="text" />
<br/>
<label >Second Number</label>
<input id="TextboxSecondNumber" type="text" />
<br />
<button id="ButtonAdd">+</button>
<br />
<span id="SpanResult" />
</body>
</html>

I have put a button and two text boxes. User will input number to be added in textboxes and on click event of the button service would get called.

In JS file to make call to REST Service returning JSON, we need to make call using WinJS.xhr.

image

In above snippet

  1. url is URL of REST Service
  2. Using JSON.parse we are parsing returned text
  3. ResultSpan is span in which result is being displayed.

Putting all code together as below,

default.js


(function () {
'use strict';


WinJS.Application.onmainwindowactivated = function (e) {
if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {



Calculator();

}
function Calculator() {
var Number1 = document.getElementById('TextboxFirstNumber');
var Number2 = document.getElementById('TextboxSecondNumber');
var ResultSpan = document.getElementById('SpanResult');
var ButtonToAdd = document.getElementById('ButtonAdd');
ButtonToAdd.addEventListener('click', function () {
var baseURl = "http://test2dj8.cloudapp.net/Service1.svc/rest/add/";
var url = baseURl+Number1.value+"/"+Number2.value;
WinJS.xhr({ url: url }).then(function (r) {
var result = JSON.parse(r.responseText);
ResultSpan.innerHTML = result;
});


});

}




Creating simple Add Service

To start with let us create a WCF REST Service returning JSON as below. There is one operation contact named Add in the service and that is taking two strings as input parameters and returning integer.


[ServiceContract]
public interface IService2
{

[OperationContract]
[WebGet(UriTemplate="/Add/{Number1}/{Number2}",RequestFormat=WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json
)]
int Add(string  Number1, string Number2);


}


Service is implemented as below,


using System;

namespace MultipleBindingWCF
{

public class Service1 : IService2
{


public int Add(string Number1, string Number2)
{
int num1 = Convert.ToInt32(Number1);
int num2 = Convert.ToInt32(Number2);
return num1 + num2;
}


}
}


Next in this section we need to configure service. We need to configure service webHttpBinding to eanble it as REST Service. So in Web.Config we need to do the below changes.


<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name ="servicebehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="restbehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<endpoint name ="RESTEndPoint"
contract ="MultipleBindingWCF.IService2"
binding ="webHttpBinding"
address ="rest"
behaviorConfiguration ="restbehavior"/>
</service>
</services>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>


After configuring, Service is ready for hosting. After hosting consume service in Windows 8 Metro application.

I hope this post is useful. Thanks for reading.

6 thoughts on “Consuming JSON in Windows 8 Metro style Application using WinJS

  1. Pingback: Dew Drop – December 25, 2011 (#1,227) | Alvin Ashcraft's Morning Dew

  2. Pingback: Monthly Report December 2011: Total Posts 23 « debug mode……

  3. Hi,DHANANJAY KUMAR.

    I following to your blog builded a wcf service in vs10.

    i find your web config will have problem, first,your service tag just one end node without start node.

    second, i add the tag “

    the service cannot run and show error “not in list….” could you give me simple project,thank you

  4. and now the wcf have ran ,but i still can not get json data in winjs method,although i use navagator input url can get data……..what wrong is that……..

  5. Pingback: 70-481 vizsgafelkészítő anyagok « Balássy György szakmai blogja

  6. Pingback: 70-481 exam preparation materials « Codes from the field

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s