Click here to Skip to main content
12,066,448 members (57,076 online)
Click here to Skip to main content
Add your own
alternative version


9 bookmarked

Mobile Development using IBM Worklight and WCF

, 23 Oct 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
This article is intended to introduce IBM Worklight and its integration with WCF.

Editorial Note

This article appears in the Third Party Products and Tools section. Articles in this section are for the members only and must not be used to promote or advertise products in any way, shape or form. Please report any spam or advertising.


This article is intended to introduce IBM Worklight and its integration with WCF.

IBM Worklight is an open source application development platform for smartphones and tablets. Applications developed using Worklight can be seamlessly deployed onto Android, Iphone, Ipad, Blackberry, etc. devices.

To learn more about the features and benefits of the IBM Worklight platform visit here.

Tutorial PDFs related to IBM Worklight can be found here

To download IBM Worklight framework and to learn about its installation visit here.

Prerequisites: Reader must be familiar with WCF restful services and related hosting concepts.


IBM Worklight framework provides a complete package of solutions for mobile application development and deployment. Worklight framework provides various approaches for developing mobile browser application as well as  mobile native application development. In this article, we would be looking at how to use Worklight framework for mobile native application development, using one of its approaches called Hybrid applications.

A mobile application developed using IBM's Worklight can be easily deployed to run on more that one mobile environments such as Android, IPhone, etc.

In this demonstration I would be showcasing development of a simple native app using Worklight's hybrid application (web) approach. 

Here is the summary of steps involved in the demo application development. 

  1. Create a simple Restful WCF service 
  2. Create a Worklight adapter
  3. Create a Worklight adapter procedure to invoke the WCF service 
  4. Format the received data using server side java script and then display it on the web page.
Note: For demonstration purpose I would be self hosting the web service.

Using the code  

Step 1: Create a simple Restful service

If you are new to WCF or to restful service then you may find this article useful. You may consider reading further after going through the knowledge base article.

In order to get started, let us quickly write a simple restful service that we would be later on consuming using Worklight. Before that let us create a simple class library named RestFulServiceDemo and add a class called Employee to the library. Details of the class are shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RestFulServiceDemo
    /// <summary>
    /// Employee details
    /// </summary>
    public class Employee
        public string FirstName { get; set; }
        public string LastName { get; set; }

Let us now create a simple service contract that would allow clients to fetch the list of all employees.  Details of the contract are shown below. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace RestFulServiceDemo
    public interface IEmployeeService
        [WebInvoke(UriTemplate="/Employees", Method="GET", ResponseFormat= WebMessageFormat.Json)]
        List<Employee> GetAllEmployees();

We would now create an implementation for IEmployeeService contract. Let us call this service as EmployeeServiceImplementation. In the constructor of EmployeeServiceImplementation service we would initialize a list of employees with some sample data and then make this list accessible to the outside world. Details of EmployeeServiceImplementation are shown below. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace RestFulServiceDemo
    public class EmployeeServiceImplementation: IEmployeeService
        private List<Employee> employees;

        public EmployeeServiceImplementation()
            employees = new List<Employee>();
            employees.Add(new Employee() { FirstName = "Pankaj", LastName = "Sharma" });
            employees.Add(new Employee() { FirstName = "Om", LastName = "Sharma" });
            employees.Add(new Employee() { FirstName = "Pranav", LastName = "Sharma" });
            employees.Add(new Employee() { FirstName = "Ankush", LastName = "Sharma" });

        public List<Employee> GetAllEmployees()
            return employees;

Now we have the service contract and its implementation ready. Final step in simple web service creation is to host this service.

Create a console application called EmployeeServiceHosting and add a reference of the class library just created above. Add a class called ServiceHoster, with a main method in it. We would now write hosting related code in the main method. Details are shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.ServiceModel.Description;

namespace EmployeeServiceHosting
    public class ServiceHoster
        static void Main(string[] args)
            WebServiceHost serviceHost = new WebServiceHost(typeof(RestFulServiceDemo.EmployeeServiceImplementation), new Uri("http://localhost:8000"));
            ServiceEndpoint endPoint = serviceHost.AddServiceEndpoint(typeof(RestFulServiceDemo.IEmployeeService), new WebHttpBinding(), "");
            ServiceDebugBehavior behavior = serviceHost.Description.Behaviors.Find<ServiceDebugBehavior>();

            behavior.HttpHelpPageEnabled = false;
            Console.WriteLine("Service is up and running");
            Console.WriteLine("Press enter to quit ");


Build the console application and then run it either by double clicking the exe or by using Visual Studio.You must see the service running as shown below.  

Step 2: Create a Worklight adapter  

What is a Worklight adapter?  

As described by IBM, an adapter is a transport layer used by worklight platform to connect to different back end systems. 

The over all idea of the adapter is that a mobile application requests the adapter to fetch some resource. Adapter in turn communicates with underlying backend systems and enquires for the resource. Backend system then returns the requested resource to the adapter which the adapter finally hand overs to the mobile application.


As of now IBM offers threes type of adapters  

HTTP Adapter  
  • Http adapter is used to send and receive HTTP requests.
  • It can be used to communicate with both restful and SOAP services. 
  • More  details about Http adapter here.
SQL Adapter 
  • As the name suggests, Sql Adapter is used to communicate with the databases.
  • More details about the Sql adapter here.
Cast Iron Adapter 
  • Cast iron adapter is used in more complex scenarios.   
  • More details about the cast iron adapter here.

In this article we would be using a HTTP adapter to consume previously created employee service.

More about adapters can be found here.   

Before you go any further you need to be familiar with the basic concepts related to Worklight project creation and Worklight project folder structure. If you are not already familiar with these, don't worry you can find those here.

Step 3: Creating a simple HTTP Adapter 

I hope that by now you have downloaded Worklight framework and have done the necessary settings on the Eclipse IDE to get started.  If not then you may refer here.

As discussed earlier HTTP adapter is used to send and receive http requests. Following are the steps involved in creation of a http adapter: 

1) Open the Eclipse IDE and create a new Worklight project. Name the project as WCFConsumer. 

This how your Project Explorer should look after creation of the project. 


2) In the Project Explorer, right click the adapters folder and select New -> Worklight Adapter as shown below


 3) In the New Worklight Adapter popup window, select Project Name, Adapter Type and enter Adapter Name as shown below  and then click on the finish button.


After successful creation of the adapter a new subfolder gets generated under the 'adapters' folder by name ConsumeWcfRestAdapter. This sub folder by default has two important files one xml and another javascript file.

If you have time then it is better to get familiar with the details of these files, please refer the link here

  • Creating a procedure for the HTTP adapter 

Now we need to create a procedure that would call the restful service that we had created earlier. Creation of a procedure invloves two steps:

  1. Declaring a procedure 
  2. Defining the procedure

A procedure is declared in the xml file that automatically gets generated in the newly created subfolder of our adapter. In our case we would be declaring the procedure in ConsumeWcfRestAdapter.xml.  

Double click the xml file to declare the procedure. Using the design view of the popped up Adapter Editor, mention below shown details for the connection policy node.

 Now, using the remove button remove existing procedure declarations if any. Then click the add button and enter procedure related details as shown below.

Now we are done with the procedure declaration part. Next step is to define the procedure.

Open the ConsumeWcfRestAdapter-impl.js. Remove all existing content and paste the code snippet shown below. 

function getEmployees() {
	var path = 'Employees';

	var input = {
		method : 'get',
		returnedContentType : 'json',
		path : path


	return WL.Server.invokeHttp(input);

In the above function 'Employees' refers to the last part of the url http://localhost:8000/Employees. WL.Server.invokeHttp(input) is responsible for sending appropriate http request to the service and for receiving the response.

Here we are done with the procedure declaration and definition. Now before invoking this procedure we need to build the adapter and depoly the code to the Worklight server. In order to do this right click the subfolder under the 'adapters' folder and follow RunAs -> Deploy Adapter as shown below.



Now we are ready to invoke the adapter. Before invoking the procedure ensure that the web service is running. In order to invoke the adapter right click the subfolder in the adapters folder and select RunAs -> Invoke Worklight Procedure as shown below. 



 In the pop up window select Project Name, Adapter Name and Procedure Name and then click the run button as shown below. 

If you have followed all the steps so far correctly then the json data fetched from the service should get displayed in the editor as shown below. 

Congratulations! you have just managed to create your first worklight procedure. It is that simple!

Step 4: Accessing service data in the mobile application 

We have reached our last step of the demonstration. Now we would be displaying the received data in the mobile application's UI.  

In the Project Explorer double click the WCFConsumer.html node located under apps -> WCFConsumer -> Common -> js and open the file.

 Clear existing contents and paste the snippet shown below.

<!DOCTYPE html>		
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0" />
		<link rel="shortcut icon" href="images/favicon.png" />
		<link rel="apple-touch-icon" href="images/apple-touch-icon.png" />
		<link rel="stylesheet" href="css/WCFConsumer.css" />
	<body id="content" style="display: none">
		<div id="invokeResult"></div>
		<script src="js/initOptions.js"></script>
		<script src="js/WCFConsumer.js"></script>
		<script src="js/messages.js"></script>

Note that in the above snippet we have added a div, with its id set to 'invokeResult'.  We would be appending the data fetched from the web service to this div.

 Now open the WCFConsumer.js file. Clear existing contents and paste the snippet shown below.

// Worklight comes with the jQuery framework bundled inside. If you do not want to use it, please comment out the line below.
window.$ = window.jQuery = WLJQ;

function wlCommonInit() {

function GetEmployeeData() {
	var invocationData = {
		adapter : 'ConsumeWcfRestAdapter',
		procedure : 'getEmployees'

	WL.Client.invokeProcedure(invocationData, {
		onSuccess : handleSuccess,
		onFailure : handleFailure,

function handleSuccess(result) {
	var httpStatusCode = result.status;
	var div = $("#invokeResult");
	if (200 == httpStatusCode) {
		var invocationResult = result.invocationResult;
		var isSuccessful = invocationResult.isSuccessful;
		if (true == isSuccessful) {
			var result = invocationResult.array;
			for ( var i = 0; i < result.length; i++) {
				div.append('FirstName: ' + result[i].FirstName);
				div.append('LastName: ' + result[i].LastName);

		} else {
			div.append("Request Failed!");
	} else {
		div.append("Request Failed!");

function handleFailure(result) {
	var div = $("#invokeResult");
	div.append("Request Failed!");

 The wlCommonInit function in the above snippet gets automatically called after the page load. Any code that you want to call immediately after the page load can be placed here. We would be placing GetEmployeeData method here. In the GetEmployeeData function we are calling the previously delcared adapter procedure getEmployees.

In the invokeProcedure method we have mentioned two handlers one for success scenario and the other for failure.  In the handleFailure function we simple display an error message.

Important functionality is in the handleSuccess function. In this function we are receiving the data from the web service in the result variable. Then we check for the status code and if everything is ok we simply append the contents to the div.

 Now right click the WCFConsumer folder under the apps folder and select New -> Worklight Environment. This pops up a window. Select Project Name, Application name and check boxes as shown below and click finish. 


 We are done! Now in order to deploy the code, right click WCFConsumer folder and select Run As -> Build All and Deploy.

Once done with the deployment open this url in the browser http://localhost:8080/console/index.html. You do not need to be connected with the internet to access this page. This web page is called Worklight Console.



 Click the preview button next to each environment and see how the application would look like. After clicking preview, web page show below gets displyed. 


Here we have managed to create an app for Android, Iphone and Ipad using IBM Worklight and WCF.

I would be more than glad to answer any queries pertaining this topic.




This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Pankaj P Sharma
Software Developer Fast Track Software Services Pvt Ltd.
India India
Currently, Pankaj works as a Software Developer at Fast Track Software Services Pvt Ltd. He is fond of both reading and programming. Pankaj also likes to experiment with new upcoming technologies.

You may also be interested in...

Comments and Discussions

QuestionReg soap service Pin
kumar301030-Dec-12 6:31
memberkumar301030-Dec-12 6:31 
Hi can you please tell me how do you consume if the service is soap
from worklight
AnswerRe: Reg soap service Pin
Pankaj P Sharma30-Dec-12 18:44
memberPankaj P Sharma30-Dec-12 18:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.160208.1 | Last Updated 23 Oct 2012
Article Copyright 2012 by Pankaj P Sharma
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid