Page tree
Skip to end of metadata
Go to start of metadata

Smartface supports most of the JavaScript libraries out there which doesn't require DOM by design. In general, we're putting main vendors' libraries under their separate folders.

With this ready to use library in Smartface, it is quick and easy to develop mobile apps with Oracle MCS capabilities.

Oracle MCS lib is created by Oracle itself. We've made a few changes on it to be sure it will work in Smartface apps seamlessly. You are also free to extend this library with additional Oracle Cloud services.

What is Oracle MCS?

Oracle has released the much anticipated Mobile Cloud Service (or MCS for short). Unlike other cloud offerings, MCS is focused not only on providing enterprise quality Mobile Backend as a Service (MBaaS), but also providing easy to use tools for business professionals to analyze and mine data about the usage of the MBaaS.

Which APIs does MCS Provide?

To help simplify mobile app development, Mobile Cloud Service provides these built-in APIs:

  • Push Notification
  • Data Offline / Sync
  • Mobile User Management
  • Analytics
  • Mobile Storage
  • Device Management

You can read more at https://blogs.oracle.com/mobile/entry/introducing_oracle_mobile_cloud_service

Using Smartface and Oracle MCS, you can develop native iOS and Android apps with cloud features just with JavaScript knowledge.

What is Smartface MCS JavaScript library?

Oracle MCS team releases Javascript  a few months behind of their REST API. We're continuously updating Smartface implementation of Oracle MCS JS SDK as soon as they release a new one. Also we're adding ready-to-use functions within a separate file named smartface.mcs.js.

These functions reflects MCS SDK and makes life easier for a Javascript developer. Some of the functions are developed by Cordova and used with a reference in our side.

  • Authentication
    • authAnonymous Anonymous authentication (for Analytics events)
    • authenticate User and password based authentication against Oracle MCS Mobile User Management. (A user has to be authenticated before using permission based applications like Storage)
  • Analytics
    • logAnalytics to Log an event
    • flushAnalytics to send your Analytics event queue to Oracle servers. All events will be logged locally until they are flushed.
    • logAndFlushAnalytics to immediately logs and flushes it.
  • Storage
    • getCollection to get a named storage collection
    • getStorageObjects to get storage objects as JSON for a collection
    • getStorageObject to download an object from given storage for a given id.
    • deleteStorageObject to delete an object from given collection for a given id
    • postObject to upload a StorageObject to your storage
    • uploadFile to upload a file to your storage. (handles StorageObject itself)
  • Notifications (Push Notification)
    • registerNotification to register the current app running on the device for receiving push notifications.
    • deRegisterNotification to deregister the app from Oracle MCS Notification system

How to use?

First, obtain Smartface JS Libs and place them inside your scripts folder in your workspace. 

If you look at Oracle folder you'll see 3 different JavaScript files;

  • libs/Oracle/mcs.js  - MCS main library developed by Oracle
  • libs/Oracle/oracle_mobile_cloud_config  - MCS config file for your API keys and tokens provided by Oracle
  • libs/Oracle/smartface.mcs.js  - Smartface Oracle backend library maintained by Smartface

Second; you have to add your keys and tokens in config file.

After configuration is done, you can simply include your libs/Oracle/smartface.mcs.js library to start using Oracle MCS. It will automatically load other necessary MCS lib modules during runtime.

Sample Usage

App Flow

To demonstrate lib usage we'll go through following steps; 

  • App Start
  • Login (if Authenticated)
    • Register for Push notifications
      • Register against Google GCM / Firebase and Apple APNS
      • Regiter against Oracle MCS 
    • Get Storage Objects
      • Get Collection (if success)
        • Get Collection Objects (if success)
          • Get Object
          • Delete Object
          • Upload a File
    • Get logged in user data.

Please consider that we'll not give detailed application UI operations in our samples. You can find MCS related functions below. 

App Start / Setting up and a simple event logging

As a best practice connect your MobileCloudService in Application_OnStart()

//including both Oracle MCS SDK and Smartface lib together
include("libs/Oracle/smartface.mcs.js");

// Setting our collection name to use it in globally in our app
var mcsCollectionName = "MyPhotos_Collection";
var myStorageCollection; //will be used for file-ops


Application.onStart = Application_OnStart;

// Application on start
function Application_OnStart(e) {
    // add your on start codes here include("pages/index.js");

    // Creating a new Oracle MCS instance
    smfOracleMCS = new SMF.Oracle.MobileCloudService('YOUR_BACKEND_NAME');

    // logging in as anonymous user to log Analytics events
    // if you need you can auth user with .authenticate
    smfOracleMCS.authAnonymous();

    // logging an event
    smfOracleMCS.logAnalytics('Application_OnStart');

    // Sends all collected event logs to the server
    smfOracleMCS.flushAnalytics();

    // if you want you can use smfOracleMCS.logAndFlushAnalytics(eventName) function to log and flush an event immediately
}


Oracle MCS Analytics

Login / Authenticating and registering for Push Notification

MCS JS SDK is an async library. That means you need to handle callbacks carefully.  In our samples below you'll see extensive use of callbacks. This is due to very nature of async itself. 

//Setting username. We're assuming you're clicking on a Login button within a Login page which has txtUserName and txtPassword
var mcsUser = txtUserName.text;
var mcsPassword = txtPassword.text;

if ((mcsUser) && (mcsPassword)) {
    //success callback for smfOracleMCS.authenticate function
    var successCallback = function(e) {
        //Authentication is successful

        //Logging the auth event
        smfOracleMCS.logAnalytics("user authenticated in = " + mcsUser)

        //Registering for Push notification
        //Registering device to Google GCM/Firebase and Apple APNS servers
        Notifications.remote.registerForPushNotifications({
            OnSuccess: function(e) {
                //our device successfully registered to formentioned servers
                //getting push notification token
                var registrationID = Notifications.remote.token;
                var appId = "your.company.application.bundle.id";
                var appVersion = Application.version;

                //Registering device to Oracle MCS. We're using error-first pattern.
                smfOracleMCS.registerNotification(registrationID, appId, appVersion, function(err) {
                    //If there is no err then it is successful.
                    if (!err) alert("MCS Notification server error:" + JSON.stringify(err));

                    //Downloading objects from mcs storage (see step 3 below)
                    getStorageObjects();
                });

            },
            OnFailure: function(e) {
                //Push notification register failed. We're continuing to download our objects from the storage.
                //Downloading objects from mcs storage (see step 3 below)
                getStorageObjects();
            }
        });
    };

    //failure callback for smfOracleMCS.authenticate function
    var failureCallback = function(e) {
        //Authentication failed.
        alert('Username or Password is incorrect, please try again');
    }

    smfOracleMCS.authenticate(mcsUser, mcsPassword, successCallback, failureCallback)
}

Getting a collection and its objects

MCS Storage can contain several collections and each collections can contain several files. To get an object from MCS you need to get it from its collection. 

//Downloads collection objects. You can directly assign objects to a SMF.UI.RepeatBox http://docs.smartface.io/#!/api/SMF.UI.RepeatBox
function getStorageObjects() {

    //success callback for smfOracleMCS.getStorageObjects function
    var successCallback = function(collection, collectionObjects) {

        // collection is an MCS object. We'll use it in next steps.
        myStorageCollection = collection;

        //collectionObjects objects is an JSON objects
        /*
        Sample item 
       [{
            "id": "6f0b3ae0-981f-4bba-b052-384c0f3557c5",
            "name": "sf-logo.png",
            "contentLength": 37800,
            "contentType": "image/png",
            "_eTag": "\"1\"",
            "createdBy": "atakan.eser@smartface.io",
            "createdOn": "2016-06-28T08:50:54Z",
            "modifiedBy": "atakan.eser@smartface.io",
            "modifiedOn": "2016-06-28T08:50:54Z"
        }]

        */

        var myObects = collectionObjects;

		//If you wan you can directly assing objects to a SMF.UI.RepeatBox as in below
        //rptBoxObjects.dataSource = myObects;
        //rptBoxObjects.refresh();
		
		// add your logic here
    };

    //failure callback for smfOracleMCS.getStorageObjects function
    var failureCallback = function(e) {
        alert(e);
    }

    smfOracleMCS.getStorageObjects(mcsCollectionName, successCallback, failureCallback);
}

Reading an object

When you call smfOracle.getStorageObjects you'll get a JSON array of object including objects ID and some meta values. You can simply use an object's ID to retrieve it from the storage

// Download file from the Storage and get file's path.
function getStorageObject(id) {
    // Retrieving object for given id (if id passed)
    if (id) {
    	//success callback for smfOracleMCS.getStorageObject function
        var successCallback = function(filePath) {

			//each object requests creates a temp file in device's app temp storage and returns its path
			//Use this file.path to display objects.
			//SMF.Utils.Fileviewer() is a Javascript library by Smartface 
			//Download from https://github.com/smartface/smf-js-libs/blob/master/libs/Smartface/fileviewer.js
            var fileViewer = new SMF.Utils.Fileviewer();
            fileViewer.openDocument(filePath);

        };

    	//failure callback for smfOracleMCS.getStorageObject function
        var failureCallback = function(e) {
            alert(id + ' cant retrieved ' + JSON.stringify(e));
        }

        smfOracleMCS.getStorageObject(myStorageCollection, id, successCallback, failureCallback)
    }
    else {
        Dialog.removeWait();
        alert('Please select a file to view');
    }
}

Deleting an object

Deleting and object from storage works a little bit different from Reading under the hood. But we have created almost similar function with a similar signature to make things easier.

// Delete file from collection
function deleteStorageObject(id) {

    // Deleting object for given id (if id passed)
    if (id) {
    	//success callback for smfOracleMCS.deleteStorageObject function
        var successCallback = function(e) {
			//After deleting an object it is suggested to refresh our collection
            getStorageObjects();
        };

    	//failure callback for smfOracleMCS.deleteStorageObject function
        var failureCallback = function(e) {
            alert(id + ' cant deleted ' + JSON.stringify(e));
        }

        smfOracleMCS.deleteStorageObject(myStorageCollection, id, successCallback, failureCallback);
    }
}   

Creating a new object in storage (Uploading a file)

To create a new file you need to get Blob object from your target file and pass it to smfOracle.uploadFile. It is suggested to read Binary Data guide. 

Lets upload a bitmap image from our app.

function uploadFile(){
    //success callback for smfOracleMCS.uploadFile function
	function successCallback(e) {
		//After uploading an object it is suggested to refresh our collection
    	getStorageObjects();
	}

    //failure callback for smfOracleMCS.deleteStorageObject function
    var failureCallback = function(e) {
		alert('Cant  upload the file ' + JSON.stringify(e));
    }

	//my_Birthday_Photo.png is in your app's image directory.
	//If you want you can get images from camera or device gallery
	//Camera Guide https://smartface.atlassian.net/wiki/display/GUIDE/Camera+Usage 
	//Device Gallery Guide https://smartface.atlassian.net/wiki/display/GUIDE/Accessing+Device+Gallery

	var img = new SMF.Bitmap("my_Birthday_Photo.png");
	var blobData = img.getBlob();

	smfOracleMCS.uploadFile(myStorageCollection, "my_Birthday_Photo.png", blobData, "images/png", successCallback, failureCallback);
}  


Getting User Data

//gets logged in User's info from MCS
function getCurrenUserData() {
    // Getting current user info from the cloud
  
    //success callback for smfOracleMCS.getCurrentUser function
    var successCallback = function(statusCode, data) {
  	   /*will return a JSON object
       {
         "id": "c9a5fdc5-737d-4e93-b292-d258ba334149",
         "username": "DwainDRob",
         "email": "js_sdk@mcs.com",
         "firstName": "Mobile",
         "lastName": "User",
         "properties": {}
       }
       */		
        var myUserData = data;
    };

    //failure callback for smfOracle.getCurrentUser function
    var failureCallback = function(e) {
        alert('Cant get the current user info from the Cloud. Please try again later!');
    }

    smfOracleMCS.getCurrentUser(successCallback, failureCallback);
}


More

You can get detailed information about Mobile Cloud Service from following web pages: