Integrating a mobile application to access SalesForce.com data with IBM Worklight and IBM WebSphere Cast Iron

How can you build a mobile application that retrieves information from a Customer Relationship Management system? Using IBM® Worklight and WebSphere® Cast Iron solutions, you will learn how you can easily and quickly deploy a mobile application for any type of smartphone or tablet that is connected to WebSphere Cast Iron to handle SalesForce®.com data.

Magali Boulet (magali.boulet@fr.ibm.com), Certified Client Technical Professional, IBM

Photo of Magali BouletMagali Boulet is a Certified Client Technical Professional and has been working for IBM since 2006. She focuses on WebSphere DataPower and WebSphere Cast Iron for customers in all industries. Prior to working for IBM, Magali had worked at several IT companies.



Etienne Noiret (etienne.noiret@fr.ibm.com), Certified Client Technical Professional, IBM

Photo of Etienne NoiretEtienne Noiret has been working for IBM since 2011 and is now focusing on mobility. Prior to working for IBM, Etienne had worked for more than 15 years in several software editors in the BPM, SOA, and JEE areas.



12 December 2012

Also available in Chinese Portuguese Spanish

Introduction

Companies are trying to cut costs, drive productivity, and provide new capabilities quickly in order to reach the maximum number of users and markets. Cloud computing and mobile are two technology drivers that enable you to meet these needs. This is why IBM has included Worklight - a Mobile Enterprise Application Platform - and IBM WebSphere Cast Iron – a cloud integration solution – together within the IBM Mobile Foundation to provide a comprehensive end-to-end solution to build, connect, manage, and secure your mobile enterprise. IBM Endpoint Manager for Mobile Devices is the third component of the IBM Mobile Foundation, which enables you to manage and secure your mobile devices. However, this component is not within the scope of this article. The intent of this article is to prove how you can easily connect a mobile application to a CRM, such as SalesForce.com, using IBM Worklight and WebSphere Cast Iron.

IBM Worklight enables rich, cross-platform application development to meet the needs of the mobile enterprise. Leveraging standard technologies and tools, such as HTML5, CSS and JavaScript, its open approach allows organizations to develop rich HTML5, hybrid, and native applications for a wide spectrum of smartphones and tablets.

IBM Worklight includes mobile-optimized middleware that serves as the gateway between the application, enterprise back-end systems, and cloud services. It is designed to integrate with the existing infrastructure of the organization and leverage its existing resources and processes.

The IBM WebSphere Cast Iron solution is a single, complete, and robust platform that is designed from the ground up to meet the specific needs of connecting all your cloud applications, all your on-premise applications, and any hybrid combination of the two sets of applications. Cast Iron Cloud integration simplifies data migration and application integration by providing everything that is needed to complete such projects using a "configuration, not coding" approach that does not require expert programmers or middleware specialization.

In this article, you will learn how you can combine Worklight productivity and Cast Iron ease-of-use to build a mobile application that retrieves SalesForce.com information.


Scenario overview

You are going to build a mobile application using Worklight and Cast Iron solutions. This mobile application will display SalesForce.com accounts. For each account chosen, it will display the associated SalesForce.com contacts.

This scenario involves three components:

  • Worklight for building the mobile application
  • Cast Iron as the middleware to connect to SalesForce.com
  • SalesForce.com as the backend Customer Relationship Management (CRM) system

The scenario is summarized as follows (see Figure 1):

  1. The user launches the Worklight application on a mobile device.
  2. The mobile application sends the user request to the Worklight server.
  3. The Worklight server uses the Cast Iron Adapter to propagate the user request to Cast Iron, issuing an HTTP GET request.
  4. Cast Iron uses its built-in SalesForce.com connector to query SalesForce.com to get the requested account or contact information.
  5. Cast Iron replies to the original Worklight server with an XML over HTTP response.
  6. The Worklight server replies to the device with a JSON over HTTP response.
Figure 1. Overview of the scenario
Overview of scenario

This article is based on WebSphere Cast Iron Studio V6.1.0.9 and IBM Worklight V5.0.3 (any edition).

Cast Iron hypothesis

For this article, we have chosen the following hypothesis for Cast Iron:

  • Worklight will communicate with Cast Iron through HTTP requests.
  • For this scenario only, parameters will be passed into the URL. To get the Contacts object of a specific account, the Account identifier (accountid) needs to be passed to Cast Iron. It will be part of the URI, for example, http://castironserver/getContacts?id=accountid. However, this is not secured, and the account identifier needs to be secured (encrypted or encoded). This article does not describe this security mechanism.
  • Since Worklight automatically transforms the XML payload into the JSON payload, Cast Iron answers to Worklight with an XML over HTTP response.
  • If no account or contact is found, or any error happens in Cast Iron, an XML error message is sent back to Worklight as follows. The Description element is populated with the origin of the error:
    <Error>
        <Name>Cast Iron Error</Name>
        <Description/>
    </Error>

In the Download section of the article, you will find the schema ErrorLog.xsd used to generate this error message.

Worklight hypothesis

For the purpose of this article, we have chosen the following hypothesis for Worklight:

  • To build the mobile application, we chose to create a hybrid application and to use the Dojo framework (jQuery or Sencha are other alternatives).
  • We did not include any graphical design elements in the mobile application that would have given a compelling user interface; we rely on what the Dojo framework provides by default.
  • We generate and optimize the application for Android® and iOS platforms, which requires that the corresponding SDKs are installed in your development environment.

Cast Iron configuration

This section explains how to create the Cast Iron project to retrieve the SalesForce.com accounts and contacts. You will be configuring two orchestrations:

  • One for retrieving the SalesForce.com accounts
  • Another one for retrieving the SalesForce.com contacts for the selected account

Retrieving the SalesForce.com accounts

  1. Open Cast Iron Studio and create a new project.
  2. Create two endpoints - one for receiving the Worklight requests and another one for SalesForce.com:
    1. From the Project tab, right-click on Endpoint and select HTTP. Leave all the default parameters (select Integration Appliance Receives Request). Rename the endpoint as HTTPReceiveRequest. You may want to create a configuration property (HttpPortIn) for the port number, as shown in Figure 2.
    Figure 2. HTTP Endpoint for receiving Worklight requests
    HTTP Endpoint for receiving Worklight requests
  3. From the Project tab, right-click on Endpoint and select Salesforce.com. Fill in the login section with your SalesForce.com account information. Again, the configuration properties for these values can be created, as shown in Figure 3.
    Figure 3. Salesforce.com Endpoint
    Salesforce.com Endpoint
  4. Click the Test Connection button at the bottom of this salesforce.com Endpoint configuration pane to test your connection. You get the following message as shown in Figure 4.
    Figure 4. Salesforce.com endpoint testing result
    Salesforce.com endpoint testing result

You are now ready to build the first orchestration:

  1. Rename the already created orchestration as getAccounts.
  2. Drag and drop the HTTPReceiveRequest Endpoint to the orchestration, and select the Receive Request Activity.
  3. In the Configure checklist, fill in /getAccounts as the URL and check the Requires a Reply option as shown in Figure 5.
    Figure 5. HTTP Receive Request activity configuration
    HTTP Receive Request activity configuration

    Now configure the SalesForce.com account query. You are going to use a Try activity to trap any error during this query.

  4. Drag and drop the Try... Activity after the HTTP Receive activity.
  5. In the Try branch, drag and drop the Salesforce.com Endpoint and select Query Objects, as shown in Figure 6.
    Figure 6. SalesForce.com Query Objects Activity
    SalesForce.com Query Objects Activity
  6. In the Configure checklist, fill in the query as SELECT Name, Id FROM Account, and validate the query using the checkbox button (highlighted with the purple circle in Figure 7).
    Figure 7. Query configuration
    Query configuration
  7. In the Map Outputs checklist, copy the SalesForce.com result objects using the Copy button, and rename the objects created variable in SFDCAccounts as shown in Figure 8 and Figure 9.
    Figure 8. Getting the SalesForce.com result
    Getting the SalesForce.com result
    Figure 9. Query Objects Activity configured
    Query Objects Activity configured

    Check if the Query Objects Activity returned anything. If yes, then you transform the SFDCAccounts XML document into a string and you send it back to Worklight. Otherwise, you send an error message back to Worklight.

  8. Within the Try branch, drag and drop the If...Then Activity after Query Objects.
  9. Configure the "If condition:" in the Left Hand Expression. Use the ellipse button to select the SFDCAccounts variable, choose the Id element, and then click OK (see Figure 10).
    Figure 10. Left Hand Expression configuration
    Left Hand Expression configuration
  10. Pick the "!=" choice for the operator. And finally enter '' as the Right Hand Expression. You get the result as shown in Figure 11.
    Figure 11. If Activity configured
    If Activity configured
  11. Drag and drop the Write XML Activity in the If branch.
  12. In the Configure checklist, choose the SFDCAccounts variable and click OK as shown in Figure 12.
    Figure 12. Choosing the XML structure to serialize
    Choosing the XML structure to serialize
  13. In the Map Inputs checklist, choose the SFDCAccounts variable and map Account from the left to Account on the right, as shown in Figure 13.
    Figure 13. Map Inputs configuration
    Map Inputs configuration
  14. In the Map Outputs checklist, use the Copy button to copy the serialization result, and rename it as SFDCAccountsString, as shown in Figure 14.
    Figure 14. Map Outputs configuration
    Map Outputs configuration

    You will then use a Map Variables Activity to populate a variable with the SalesForce.com account serialized list.

  15. Still in the If branch, drag and drop the Map Variables Activity after the Write XML one.
  16. Click the Select Inputs button and choose the SFDCAccountsString variable as shown in Figure 15.
    Figure 15. Input of the Map Variable Activity
    Input of the Map Variable Activity
  17. Click the Select Outputs button, create a new string variable (using the New button in the popup window) and name it outputMessage.
  18. Finally, map the SFDCAccountsString on the left to the outputMessage on the right, as shown in Figure 16.
    Figure 16. Final mapping of the Map Variable Activity
    Final mapping of the Map Variable Activity
  19. Finally, drag and drop the Send Response Activity after the Try block (but not in the Try block). The configure checklist is already populated with the HTTP Receive Request Activity that you configured earlier.
  20. In the Map Inputs checklist, select the outputMessage variable and map it to the body as shown in Figure 17.
    Figure 17. Configuring the result to be sent back to Worklight application
    Configuring the result to be sent back to Worklight application

    At this stage, notice the warning icon at the Map Inputs checklist of the above activity. Rolling your mouse over, you see the warning message generated by Cast Iron Studio, as shown in Figure 18.

    Figure 18. Warning message for the outputMessage variable
    Warning message for the outputMessage variable

    The variable outputMessage has not been initialized outside of the Try block. This means Cast Iron does not know the value of this variable. One solution is to assign a default value to this variable. To do so, go to the Variables tab, select the outputMessage variable, and assign a default value, such as default output message value.

    You are almost done! To complete the orchestration, you now need to configure the Else and Catch branches.

    As explained in the Cast Iron hypothesis, you will generate a custom error message based on an XML schema definition.

  21. Upload the ErrorLog XML Schema in your project (provided in the Download section of the article).
  22. In the Else branch, drag and drop the Write XML Activity:
    1. In the Configure checklist, click the Browse button, create a variable based on the ErrorLog schema, and use it as the XML schema to serialize, as shown in Figure 19.
      Figure 19. Choosing the XML structure to serialize
      Choosing the XML structure to serialize
    2. In the Map Inputs section, in the To Activity part, define the default values for the Name and Description elements as shown in Figure 20, such as Cast Iron Error as the Name and No Account found as the Description.
      Figure 20. Assigning default error values
      Assigning default error values
    3. In the Map Outputs checklist, use the Copy button to copy the serialization result, and rename it as ErrorMessage.
  23. Still in the Else branch, drag and drop the Map Variables Activity after the Write XML one. Click the Select Inputs button and choose the ErrorMessage variable. Click the Select Outputs button and choose the outputMessage variable. Map the ErrorMessage to the outputMessage variable.
  24. In the CatchAll branch, drag and drop the Write XML Activity:
    1. In the Configure checklist, choose the error variable (based on the ErrorLog schema) created earlier.
    2. In the Map Inputs section, click the Select Inputs button and choose the FaultInfo variable. Define a default value for the Name, for instance CastIron Error and map the message element of the FaultInfo variable to the description element on the right.
    3. In the Map Outputs section, map the XmlText variable to the outputMessage variable.

    Finally, go to Orchestration menu and choose the Validate option to have Cast Iron Studio validate your orchestration. You get a confirmation message saying that your orchestration is valid. Your orchestration looks similar to the one shown in Figure 21.

    Figure 21. getAccounts orchestration
    getAccounts orchestration

Retrieving SalesForce.com contacts

This orchestration will consist of querying SalesForce.com to retrieve the contacts of the selected account. It is similar to the first one, so you will copy and paste the getAccounts orchestration and modify it.

  1. Copy and paste the getAccounts orchestration. Rename it getContacts.
  2. Modify the Receive Request Activity. You will change the URL and add the account identifier extraction, since this orchestration will be receiving an HTTP request from Worklight, such as http://castironserver/getContacts?id=accountid.
    1. In the Configure checklist, change to URL to /getContacts.
    2. In the Map Outputs checklist, click the Select Outputs button, create a new string variable, and name it accountId. Click OK.
    3. Drag and drop the Substring After Function; map it to uri on the left and double-click it. Fill in the matchString parameter with id=, as shown in Figure 22. Click OK.
      Figure 22. Extraction of the Account identifier
      Extraction of the Account identifier
  3. Map the Substring After Function to accountId variable on the right.
  4. Click the Query Objects Activity:
    1. Go to the Configure checklist and modify the query to SELECT LastName, FirstName, Email FROM Contact WHERE AccountId=$idparam. Click the Validate Query button.
    2. In the Map Inputs checklist, click the Select Inputs button and choose the accountId variable. Map it to the idparam variable on the right, as shown in Figure 23.
      Figure 23. Using the Account identifier for the Contact object query
      Using the Account identifier for the Contact object query
    3. In the Map Outputs checklist, rename the variable SFDCAccounts to SFDCContacts and map the Contact object on the left to the Contact object on the right.
  5. Modify the If condition branch. In the Left Hand Expression, click the ellipse button, select the SFDCContacts variable, and pick the LastName field as shown in Figure 24.
    Figure 24. Left Hand Expression configuration
    Left Hand Expression configuration
  6. Modify the Write XML Activity in the If condition branch.
    1. In the Configure checklist, choose the SFDCContacts variable and click OK.
    2. In the Map Inputs checklist, remove the SFDCAccounts variable, and add the SFDCContacts variable. Map it to the Contact variable on the right as shown in Figure 25.
      Figure 25. Getting the SalesForce.com Contact query result to be serialized
      Getting the SalesForce.com Contact query result to be serialized
    3. In the Map Outputs checklist, rename the variable to SFDCContactsString.
  7. Modify the Map Variable Activity in the If condition branch to map SFDCContactsString to the outputMessage variable.
  8. In the Else Branch, modify the Write XML Activity. Go to the Map Inputs section and change the default value for the Description parameter to No Contact found as shown in Figure 26.
    Figure 26. Custom error message when no contact found
    Custom error message when no contact found

Again, you may want Cast Iron Studio to check if your orchestration is valid, as done earlier. You may want Cast Iron Studio to remove all the unused variables of your orchestrations. From the Variables tab, right-click in the Variables pane and choose the Remove Unused Variable(s) menu.

You are now ready to test your orchestrations. You will test locally within Cast Iron Studio, and then deploy and run it on a Cast Iron server.

Testing the orchestrations locally within Cast Iron Studio

  1. Using the Verify Tab, you will start the orchestration you want to test. You may use the HTTP Post Utility from Cast Iron Studio to send the HTTP request to the orchestration.
  2. To test the getAccounts orchestration, you may send a request such as http://hostname/getAccounts.
  3. To test the getContacts orchestration, you need to send an account identifier as part of the request URI (you may use the getAccounts result to copy one of the account identifiers). The request to be sent is similar to this URL: http://hostname/getContacts?id=<accountidentifier>.

Once your local testing is done and successful, you are now ready to deploy to the Cast Iron server.

Deploying to the Cast Iron server

  1. From Cast Iron Studio, select the menu File > Publish Project and fill in the host name, user name, and password of your Cast Iron Server, as shown in Figure 27. Keep in mind that the host name is the admin IP address.
    Figure 27. Deploying on Cast Iron Server
    Deploying on Cast Iron Server
  2. Now you may log in to your Cast Iron Server Web Management Console. You see that your project is ready to be started.

Worklight configuration

There are three main steps to build this mobile application:

  1. Design the views that the user will see and the navigation flow. This is client side development, and you will use the graphical editor of Worklight Studio for a WYSIWYG implementation.
  2. Create the connectivity to the Cast Iron services that you have exposed in the previous section. This is server side development, and you will use the adapters' capabilities of Worklight Studio to create this code.
  3. Use these services inside the views to populate them dynamically when the user navigates along the application. This is again client side development that requires adding some Javascript to the pages previously designed.

You will also need to optimize and generate the application for iOS and Android platforms.

Designing the mobile views and the navigation flow

Let's start by creating the mobile application project. Figure 28 shows how to initiate a hybrid application based on the Dojo framework.

Figure 28. Creation of the hybrid application
Creation of the hybrid application

The application is based on a typical navigation template:

  • A "main" view, used to dispatch the user to the various functions implemented
  • A pair of "master / details" views.
  1. Let's start by implementing the main view. Using the graphical editor of Worklight Studio, open the main MyCRM.html file, ensure that you are in "Design mode", and ensure that the palette is displayed. From the "Dojox.mobile" panel, drag and drop a Scrollable view widget into your main page, as shown in Figure 29, and name it mainView.
    Figure 29. Creation of the main view
    Creation of the main view
  2. In this view, drag and drop EdgeToEdgeList and create three static items by right-clicking on the first item and selecting ListItem / Insert After, as shown in Figure 30. Note that later on, you will only implement the link "My customers".
    Figure 30. Creation of the main menu
    Creation of the main menu
  3. It is now time to implement the master details views. As shown in Figure 31, take another ScrollableView from the palette, drag it after the main view, name it accountsView and include a heading with a title My Accounts, and a back button linked to the previously created "mainView". Finally, drag another EdgeToEdgeList into this view and name it accountsList. Later on, you will use the adapter to dynamically fill in this list.
    Figure 31. Creation of the Accounts view
    Creation of the Accounts view
  4. The last view to implement shows the contacts linked to an account in SalesForce.com. Switch to the source view of your HTML page, copy and paste the accountView, rename the title to Contacts" link the back button to the accountsView, and rename the list to contactsList. Figure 32 shows how the application should display (note the "Mobile views" window in the lower left corner).
    Figure 32. Summary of the Master/Details views
    Summary of the Master/Details views
  5. Finally, select mainView, right click on the My accounts item and select List Items / Link to Mobile View (see Figure 33). Select accountsView from the dropdown box, which ensures that you can go to this view when clicking on this item.
    Figure 33. Linking the main view to the Accounts view
    Linking the main view to the Accounts view
  6. At this stage, you can test your static application. Right-click on the common folder and choose Run as / Build all and Deploy. Open the Worklight console at http://localhost:8080/console to ensure that your application was deployed and click on the Preview as Common Resources link. You are now able to navigate between the main menu view and the contacts view, as shown in Figure 34.
    Figure 34. Testing the static views from the console
    Testing the static views from the console

Creating the server side code using a Worklight adapter

Worklight enables you to separate the server side code (access to the backend services) from the client side code (manipulation of data to fill in the views). The server side code can have a different lifecycle than the client side code, provided that the interface contract between the two does not change. All the server side code is written through adapters in Worklight Studio. In this scenario, we use a Cast Iron adapter to call the services that were previously exposed through Cast Iron.

  1. In Studio, select File > New > Worklight Adapter to create a new adapter, select Cast Iron from the Adapter type dropdown box, and name it CRMAdapter, as shown in Figure 35.
    Figure 35. Creating the Cast Iron adapter
    Creating the Cast Iron adapter
  2. The first file to implement is the XML descriptor of the adapter, where you can specify the connectivity to Cast Iron and declare two functions that you will implement (getAccounts and getContacts), as shown in Figure 36.
    Figure 36. Configuring the Cast Iron adapter
    Configuring the Cast Iron adapter
  3. Now you are ready to do the implementation in the Javascript file that was created together with the adapter. Figure 37 shows how easy it is to call the backend services. Note that it is also possible to:
    • Mix the Javascript and Java code.
    • Call several back end services and expose them as one single service to avoid multiple round trips between the mobile application and the server.
    • Add security constraints on top of any adapter service call.
    Figure 37. Implementing the Cast Iron remote services
    Implementing the Cast Iron remote services
  4. Make sure that the adapter services have been tested before using them in a mobile application. In the Project Explorer view, right-click on the newly created adapter, select first Run as > Deploy Worklight Adapter, and then Run as > Invoke Worklight Procedure. Figure 38 shows the invocation parameters available. Select getAccounts and click Run.
    Figure 38. Testing the Cast Iron remote services
    Testing the Cast Iron remote services
  5. Figure 39 shows the invocation result. Note that the XML that was returned by Cast Iron has automatically been transformed to a JSON format, which is the optimized way to transport data over a limited bandwidth and to manipulate data through Javascript. At this stage, note the JSON structure that you will have to go through to fill in your lists.
    Figure 39. Cast Iron remote services invocation result
    Cast Iron remote services invocation result

Dynamically filling the views using the remote adapter

You now have all the building blocks required to finish the implementation of the application. The mobile views on one side and the adapter services on the other side.

Open the main HTML file, select the My customers item in the mainView, and add a call to a getAccounts Javascript function on the onclick event, as shown in Figure 40.

Figure 40. Calling the getAccounts service on page load
Calling the getAccounts service on page load

Now let's implement the "getAccounts" function in the MyCRM.js file by making a remote call to the adapter service that was previously created. Listing 1 shows how to call this adapter through the WL.Client.invokeProcedure method and how to implement call back functions to handle the result.

Listing 1. Javascript code to dynamically fill the Accounts list
var busy;

function wlCommonInit(){
    // Common initialization code goes here
    busy = new WL.BusyIndicator('content', {color : '#1D4885'});
    busy.hide();
}

function getAccounts() {
    busy.show();
    var invocationData = {
            adapter: 'CRMAdapter',
            procedure: 'getAccounts',
            parameters: []
    };
    WL.Client.invokeProcedure(invocationData, {
        onSuccess : onGetAccountsSuccess,
        onFailure : onGetAccountsFailed,
        timeout : 30000
    });
}

function onGetAccountsSuccess(response) {
    busy.hide();
    var items = dijit.registry.byId("accountsList");
    items.destroyDescendants();
    if(response.invocationResult.Error) {
        // Functional error returned by CI
        WL.SimpleDialog.show("Error",
         "CRM returned error: " + response.invocationResult.Error.Description,
         [{text : "Close"}]);
    } else {
        var accounts = response.invocationResult.objects.Account;
        if(accounts && accounts.length>0) {
            for(var i=0; i<accounts.length; i++) {
                var account = accounts[i];
                var item = new dojox.mobile.ListItem({
                    moveTo: "contactsView",
                    transition: "slide",
                    label: account.Name
                });
                items.addChild(item);
                item.on("click", dojo.hitch(account, function() 
                 { searchContacts(this); }));
            }
        }
    }
}

function onGetAccountsFailed(response) {
    busy.hide();
    WL.SimpleDialog.show("Error",
            "Failed to connect to back end" + (response.errorMsg ? ": " 
              + response.errorMsg : ""),
            [{text : "Close"}]);
}

When the call to the remote adapter succeeds, the onGetAccountsSuccess method is called. It is the right place to loop through the accounts retrieved from the backend and dynamically fill in the "accountsList" widget that you previously created. Listing 1 also shows how you can dynamically create Dojo widgets in Javascript. Note that you also implement a call to the searchContacts function on each item and pass the current account ID to this function.

The implementation of the searchContacts function is similar to the getAccounts function, except that the items that you create are not clickable. Listing 2 shows the contact data you will display in each item.

Listing 2. Javascript code to invoke searchContacts
function searchContacts(account) {
    busy.show();
    var invocationData = {
            adapter: 'CRMAdapter',
            procedure: 'getContacts',
            parameters: [account.Id]
    };
    WL.Client.invokeProcedure(invocationData, {
        onSuccess : onSearchSuccess,
        onFailure : onSearchFailed,
        timeout : 30000
    });
}

function onSearchSuccess(response) {
    busy.hide();
    var items = dijit.registry.byId("contactsList");
    items.destroyDescendants();
    if(response.invocationResult.Error) {
        // Functional error returned by CI
        WL.SimpleDialog.show("Error",
         "CRM returned error: " + response.invocationResult.Error.Description,
         [{text : "Close"}]);
    } else {
        var contacts = response.invocationResult.objects.Contact;
        if(contacts && contacts.length>0) {
            for(var i=0; i<contacts.length; i++) {
                var contact = contacts[i];
                var item = new dojox.mobile.ListItem({
                    label: contact["FirstName"] + ' ' + contact["LastName"] + ' 
                     (' + contact["Email"] + ')'
                });
                items.addChild(item);
            }
        }
    }
}

function onSearchFailed(response) {
    busy.hide();
    var items = dijit.registry.byId("contactsList");
    items.destroyDescendants();
    WL.SimpleDialog.show("Error", "Failed to connect to back end" + 
     (response.errorMsg ? ": " + response.errorMsg : ""), [{text : "Close"}]);
}

Optimizing the application for different target mobile operating systems

Now that your application is ready, you have to choose which target environments you will deploy to and what kind of optimization you want to apply to each of these environments. Worklight Studio helps you to optimize the application based on a common code (what you have developed so far) so that you have a unique experience adapted to the operating systems and devices where the app will be executed. For the purpose of this demonstration, you will create an iPhone® and an Android environment. Select File > New > Worklight Environment, as shown in Figure 41. You will then implement an optimization for the Android environment only.

Figure 41. Adding iPhone and Android OS
Adding iPhone and Android OS

For the Android environment, note the system back button that people are using to navigate back into their applications. This requires one small modification into the common directory and a dedicated implementation into the Android directory. As shown in Figure 42, add a global variable and a Javascript function into the common directory to memorize the current view.

Figure 42. Managing the navigation
Managing the navigation

Then in the Android directory, implement a Javascript function into the MyCRM.js file that handles the navigation each time a user clicks on the system back button, based on the current view. Listing 3 shows how this is implemented.

Listing 3. Optimizing the navigation for Android
function wlEnvInit() {
    wlCommonInit();
    // Environment initialization code goes here
    initBackButton();
}

function initBackButton() {
    WL.App.overrideBackButton(backKeyDownFunction);
}

function backKeyDownFunction(){
    switch (currentView.id) {
        case "contactsView":
            currentView.performTransition('accountsView',-1,"slide",null);
            currentView = dijit.registry.byId("accountsView");
            break;
        case "accountsView":
            currentView.performTransition('mainView',-1,"slide",null);
            currentView = dijit.registry.byId("mainView");
            break;
        default:
            navigator.app.exitApp();        
    }
}

In addition, you can also update the Android MyCRM.css file to hide the back buttons that are displayed in the headers, as shown in Listing 4.

Listing 4. Hiding the back button for Android
/* Hide the Dojo Mobile back button on Android */
.mblToolBarButtonHasLeftArrow {
    display: none;
}

Once done, ensure that all your files are saved, select the application from the Project Explorer view, right-click and select Run as > Build all and Deploy. You are now ready to test the final application.


Putting it all together

First, you can test the application through the mobile browser simulator. Open the Worklight console (http://localhost:8080/console) and click either Android or iPhone and test the application, as shown in Figure 43.

Figure 43. Testing the final application with mobile browser simulator
Testing the final application with mobile browser simulator

This technique is useful to debug all your Javascript code and CSS using the built-in browser debuggers that are available. Then, you can generate the binary application that will be deployed on each physical device. Make sure your mobile devices are on the same network of your Worklight Server by using, for example, a common WIFI access.

Let's start with the Android application. As the Android development kit is based on Java, the native Android project has already been deployed in Eclipse (the Android SDK must be already installed) under a project with the same name as your project or application, plus the Android suffix such as “SalesMyCRMAndroid” in our case.

Connect your physical device through a USB cable onto your machine. Make sure you have installed the driver of your mobile device, and make sure your Android device has enabled the “USB Debug Mode”. Then select the created Android project in Eclipse by right-clicking and selecting Run as > Android Application. It automatically deploys the apk binary to your mobile device and you are ready to test the application, as shown in Figure 44. Make sure the back button enables you to navigate between the views, as you have implemented this part for the Android environment.

Figure 44. Final application on Android
Final application on Android

For the iPhone environment, it is mandatory to compile the application using a development tool called Xcode, which is only available on MacOS. Therefore, when you run your Eclipse on a MacOS environment, you can right-click on the iPhone folder and select Run as > Xcode project, as shown in Figure 45.

Figure 45. Generating the application for iOS
Generating the application for iOS

Once generated, the Xcode studio is automatically launched and you can directly test the application using the built-in simulator. You can also update the settings of the project with your Apple® Provisioning Profile to generate and sign the binary (ipa file) that can then be deployed on a real device. Figure 46 shows what the application looks like on the iPhone simulator.

Figure 46. Testing the application with iPhone simulator
Testing the application with iPhone simulator

Figure 47 shows what the application looks like when it is deployed on an iPhone. The back buttons in the headings are visible to ensure the correct navigation on the iPhone.

Figure 47. Final application on the iPhone
Final application on the iPhone

Finally, you can open the Cast Iron Web Management Console to monitor the Worklight calls, as shown in Figure 48.

Figure 48. Cast Iron Web Management Console
Cast Iron Web Management Console

Also, you can dig into each orchestration execution. When the log level is enabled to debug, you can see a detailed view of each activity within this orchestration, as shown in Figure 49.

Figure 49. Detailed view of the getContacts orchestration
Detailed view of the getContacts orchestration

Possible extensions to the application

A more advanced version of this application adds the following capabilities:

  • Notifications: Worklight provides a unified notification API that you can use on the server side to send notifications to the mobile applications. Cast Iron can subscribe to an event in SalesForce.com, such as a change on an account or a contact, call an HTTP adapter on Worklight Server that would in turn create a notification message, and send it to the end user in charge of the account. The mobile application is enhanced to handle this message.
  • Security: Worklight provides a simple, but yet powerful, way to control the authentication and access to the backend services. By implementing either an authentication on startup or on demand, the identity of the authenticated user is used in the parameter to the call to Cast Iron. Cast Iron takes into account this information in its query to filter the accounts that are linked to the current user.

Conclusion

Part of IBM Mobile Foundation, IBM Worklight and WebSphere Cast Iron enable you to quickly build and run mobile applications that are connected to your backend systems. To speed up the development, Cast Iron focuses on the simplicity where no code is requested, just configuration of flows. On the other side, Worklight focuses on standards (HTML5, open source graphical libraries) so that you can reuse existing skills set to build the mobile applications. Worklight provides a clear separation between the client and the server side code. The Worklight server acts as a mobile middleware and ensures the mobile application management of your applications.


Downloads

DescriptionNameSize
Code sampleWL-CI-download.zip24368KB
Code sampleErrorLog.xsd1KB

Resources

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into WebSphere on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=WebSphere, Mobile development
ArticleID=851286
ArticleTitle=Integrating a mobile application to access SalesForce.com data with IBM Worklight and IBM WebSphere Cast Iron
publish-date=12122012