Wednesday, July 10, 2013

Consuming WCF Service from JavaScript – JSON

Just ordered a full Hot ‘n’ Spicy Peperoni Pizza from Dominos (if you have some other suggestion, please do comment them on this post.) Also ordered a bottle of Coca Cola, which will be arriving at anytime (within 30 minutes, as they say). I have to finish writing this post before it do. So straight away moving onto the main content of the post, which is simply creating a WCF service, hosting it with JSON end point and consuming it with JavaScript.

In order to do this, let’s create a Windows 8 blank application project.

image

Add new project to the solution.

image

And choose WCF service application template.

image

So, we have two projects in one solution.

Creating Service

Creating a WCF service is very easy, as we’d already seen before. You might want to look at the following link, in order to create the service that we are going to use tonight. As you have seen already, our service has a function SayHello(), that returns a string saying “Hello World!”. Right now the service is using SOAP to communicate with clients (the programs that uses the service). Here, since our client is JavaScript which doesn’t understand SOAP, we need to communicate it with something that it can interpret, a format that it can understand. And the format is, JSON. Applause!!!

JSON

Here, we will create a restful service and using HTTP’s GET, we will fetch the data from the service. Some modifications in Web.config and little tweak in code will do that for us.
In the interface IHelloWorldService write exactly the following lines:

   1: [ServiceContract]
   2:    public interface IHelloWorldService
   3:    {
   4:        [OperationContract]
   5:        [WebGet(UriTemplate = "/SayHello", RequestFormat = WebMessageFormat.Json, 
   6:                                         ResponseFormat = WebMessageFormat.Json)]
   7:        string SayHello();
   8:    }

Here, we’ve set both Request and Response format of the service as JSON. Now in Web.Config, we need to create an endpoint for webHttpBinding so as to enable service to use Http’s GET method. Let me tell you exactly how it can be done. Click open Web.config file. When the file open, create the service end point and behavior as mentioned in the XML below.

   1: <?xml version="1.0"?>
   2: <configuration>
   3:  
   4:   <appSettings>
   5:     <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
   6:   </appSettings>
   7:   <system.web>
   8:     <compilation debug="true" targetFramework="4.5" />
   9:     <httpRuntime targetFramework="4.5"/>
  10:   </system.web>
  11:   <system.serviceModel>
  12:     <services>
  13:       <service name="HelloWorldService.IHelloWorldService" 
  14:                         behaviorConfiguration="ServiceBehaviour">
  15:         <endpoint binding="webHttpBinding" bindingConfiguration=""
  16:                                  behaviorConfiguration="webhttpconfig"
  17:           contract="HelloWorldService.IHelloWorldService" />
  18:       </service>
  19:     </services>
  20:     <behaviors>
  21:       <serviceBehaviors>
  22:         <behavior name="ServiceBehaviour">
  23:            <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
  24:            <serviceDebug includeExceptionDetailInFaults="false"/>
  25:         </behavior>
  26:       </serviceBehaviors>
  27:     <endpointBehaviors>
  28:         <behavior name="webhttpconfig">
  29:           <webHttp/>
  30:         </behavior>
  31:       </endpointBehaviors>
  32:     </behaviors>
  33:     <protocolMapping>
  34:         <add binding="webHttpBinding" scheme="https" />
  35:     </protocolMapping>    
  36:     <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
  37:                      multipleSiteBindingsEnabled="true" />
  38:   </system.serviceModel>
  39:   <system.webServer>
  40:     <modules runAllManagedModulesForAllRequests="true"/>
  41:     <!--
  42:         To browse web app root directory during debugging, set the value below to true.
  43:         Set to false before deployment to avoid disclosing web app folder information.
  44:       -->
  45:     <directoryBrowse enabled="true"/>
  46:   </system.webServer>
  47:  
  48: </configuration>

As you can see we have created an endpoint line #15 and endpoint behavior configuration in line #27. That’s it, we are done. To test the service, in the WCF project right click on the HelloWordService.svc file and choose View in Browser.

SNAGHTML7c680480

Append the name of the function SayHello in the url as shown below. On pressing enter, internet explorer will ask you to download the file as it is not able to display JSON. And if it does, then congrats, you have just created a RESTful service.

image

We are done with service part. Now comes consuming the service.

Consuming Service

As of now, we were working with WCF project, time to move onto Windows8 part. In default.html file, as usual, I have given ID to the paragraph tag that was presented to me by default.

   1: <body>
   2:     <p id="allHTML">Content goes here</p>
   3: </body>

All the magic will happen in the default.js file. And the magic happens only because of the following function.

   1: function getContentFromWeb() {
   2:         //WCF service URL
   3:         var link = "http://localhost:16913/HelloWorldService.svc/SayHello";
   4:                 WinJS.xhr({ url: link }).then(
   5:                        function (responce) {
   6:                            var allHtml = document.getElementById("allHtml");
   7:                            allHTML.innerText = JSON.parse(responce.responseText);
   8:                        }
   9:                   );
  10:            }

Where link is the URL of the service’s function, which we want to GET data from. We fire the query and will download everything the service provides. Once we get everything, we parse that everything into something that we can use. In this case, the text “Hello World!”. Whatever we get after parsing the responceText, it get’s displayed onto the screen via the paragraph tag.
Finally, we call the function getContentFromWeb() just after the application starts.

   1: app.onactivated = function (args) {
   2:        if (args.detail.kind === activation.ActivationKind.launch) {
   3:            if (args.detail.previousExecutionState !==
   4:                          activation.ApplicationExecutionState.terminated) {
   5:              getContentFromWeb();
   6:            } else {
   7:                // TODO: This application has been reactivated from suspension.
   8:                // Restore application state here.
   9:            }
  10:            args.setPromise(WinJS.UI.processAll());
  11:        }
  12:    };

Preparing the solution

One last step to set it all work is to set both the projects as the startup project. As a service needs to be running when we use it. To do this, right click on the solution and choose set startup projects. In the dialog box open set the settings exactly as shown below.

image

Click OK and you’re done. Hit F5 and see the magic happening.
Ahh!!! here comes my Pizza, you enjoy the post and I'll go enjoy my delicious pizza

Happy Reading!!!

Share this post

0 comments

:) :-) :)) =)) :( :-( :(( :d :-d @-) :p :o :>) (o) [-( :-? (p) :-s (m) 8-) :-t :-b b-( :-# =p~ :-$ (b) (f) x-) (k) (h) (c) cheer

 
© 2013 Neelesh Vishwakarma
Posts RSS Comments RSS
Back to top