Warning Older Docs! - You are viewing documentation for a previous released version of RhoMobile Suite.

RhoConnectClient

RhoConnectClient is used for synchronization with RhoConnect applications.

Enabling the API

In order to use this API you must include the following extension in your build.yml

extensions: ["rhoconnect-client"]

JavaScript Usage

Be sure to review the JavaScript API Usage guide for important information about using this API in JavaScript

Ruby Usage

Be sure to review the Ruby API Usage guide for important information about using this API in Ruby

Methods

addObjectNotify(STRING sourceName, STRING object)

Replaces: add_objectnotify

Add the object notification by passing in an object ID.

Parameters

  • sourceName : STRING

    Source name for object notification.

  • object : STRING

    Object ID to get notifications.

Synchronous Return:

  • Void

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • JavaScript: Rho.RhoConnectClient.addObjectNotify(STRING sourceName, STRING object)
    • Ruby: Rho::RhoConnectClient.addObjectNotify(STRING sourceName, STRING object)

cleanObjectNotify()

Replaces: clean_objectnotify

Removes callback for object notifications.

Synchronous Return:

  • Void

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • JavaScript: Rho.RhoConnectClient.cleanObjectNotify()
    • Ruby: Rho::RhoConnectClient.cleanObjectNotify()

clearNotification(STRING sourceName)

Clears the sync notification for a given source.

Parameters

  • sourceName : STRING

    Source name to clear notification. Use ‘*’ to clear notification for all models.

Synchronous Return:

  • Void

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • JavaScript: Rho.RhoConnectClient.clearNotification(STRING sourceName)
    • Ruby: Rho::RhoConnectClient.clearNotification(STRING sourceName)

doSync(BOOLEAN showStatusPopup, STRING queryParams, BOOLEAN syncOnlyChangedSources)

Replaces: dosync

Start the RhoConnectClient sync process.

Parameters

  • showStatusPopup : BOOLEAN Optional

    Set to true to show status popup.

  • queryParams : STRING Optional

    Parameters to be passed to server.

  • syncOnlyChangedSources : BOOLEAN Optional

    Sync only sources that have local changes.

Synchronous Return:

  • STRING

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • JavaScript: Rho.RhoConnectClient.doSync(BOOLEAN showStatusPopup, STRING queryParams, BOOLEAN syncOnlyChangedSources)
    • Ruby: Rho::RhoConnectClient.doSync(BOOLEAN showStatusPopup, STRING queryParams, BOOLEAN syncOnlyChangedSources)

doSyncSource(STRING sourceName, BOOLEAN showStatusPopup, STRING queryParams)

Start RhoConnectClient sync process for a given source name.

Parameters

  • sourceName : STRING

    Source name.

  • showStatusPopup : BOOLEAN Optional

    Set to true to show status popup.

  • queryParams : STRING Optional

    Parameters to be passed to server.

Synchronous Return:

  • STRING

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • JavaScript: Rho.RhoConnectClient.doSyncSource(STRING sourceName, BOOLEAN showStatusPopup, STRING queryParams)
    • Ruby: Rho::RhoConnectClient.doSyncSource(STRING sourceName, BOOLEAN showStatusPopup, STRING queryParams)

enable_status_popup(BOOLEAN true_or_false)

Enable or disable the show status popup.

Parameters

  • true_or_false : BOOLEAN Default: false

    • true : BOOLEAN

      Enable the status popup.

    • false : BOOLEAN

      Disable the status popup.

Synchronous Return:

  • Void

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • Ruby: Rho::RhoConnectClient.enable_status_popup(BOOLEAN true_or_false)

get_pagesize()

Returns the current sync page size for the RhoConnectClient.

Synchronous Return:

  • INTEGER :

    Page size for the RhoConnectClient.

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • Ruby: Rho::RhoConnectClient.get_pagesize()

get_user_name()

Returns the current username of the RhoConnectClient session.

Synchronous Return:

  • STRING :

    Username of current user if logged in, last logged in user if not logged in.

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • Ruby: Rho::RhoConnectClient.get_user_name()

isLoggedIn()

Returns true if the RhoConnectClient currently has a user session, false if not.

Synchronous Return:

  • BOOLEAN :

    True if have logged in user session, false if not.

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • JavaScript: Rho.RhoConnectClient.isLoggedIn()
    • Ruby: Rho::RhoConnectClient.isLoggedIn()

isSyncing()

Returns true if sync is currently in progress.

Synchronous Return:

  • BOOLEAN :

    True if sync has started but not finished yet, false otherwise.

Method Access:

  • Class Method: This method can only be accessed via the API class object.
    • JavaScript: Rho.RhoConnectClient.isSyncing()
    • Ruby: Rho::RhoConnectClient.isSyncing()

login(STRING login, STRING password, CallBackHandler callback)

Authenticates the user with RhoConnect. The callback will be executed when it is finished.

Parameters

  • login : STRING

    Login name.

  • password : STRING

    Password.

  • callback : CallBackHandler Mandatory

Async Callback Returning Parameters: INTEGER

    Synchronous Return:

    • INTEGER : this method also supports async callbacks - check the Callback tab for callback return parameters.

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.RhoConnectClient.login(STRING login, STRING password, CallBackHandler callback)
      • Ruby: Rho::RhoConnectClient.login(STRING login, STRING password, CallBackHandler callback)

    logout()

    Logout the user from the RhoConnect server. This removes the local user session.

    Synchronous Return:

    • Void

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.RhoConnectClient.logout()
      • Ruby: Rho::RhoConnectClient.logout()

    on_sync_create_error(STRING source_name, ARRAY objects, SYMBOL action)

    Perform an action on a record upon a sync create-error. The :recreate action will write the records to the local DB and schedule them to be pushed to the back-end again at the next sync. For example, if a create-error occurred because something was missing but it is mandatory for validation. You can use the :recreate flag after catching the error in order resend a fixed record. The :delete action will permanently delete a record on the local DB and will never be synced with the back-end. This might be used in cases where a time-stamp is vital and upon error, a new record must be generated before syncing.

    Parameters

    • source_name : STRING

      The ORM model name. This is necessary for RhoConnect to know the model on which the action is to be performed.

    • objects : ARRAY

      An array of one or more object IDs. These IDs are the IDs of the objects that failed to create.

    • action : SYMBOL

      Action to be performed on the objects specified in the objects array.

      • :delete : STRING

        Remove the object from the local DB and do not retry creation of the record on the back-end.

      • :recreate : STRING

        Push this object to the server again at the next sync.

    Synchronous Return:

    • Void

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • Ruby: Rho::RhoConnectClient.on_sync_create_error(STRING source_name, ARRAY objects, SYMBOL action)

    on_sync_delete_error(STRING source_name, HASH objects, SYMBOL action)

    Decide whether or not to retry deletion of a record upon a sync delete-error. In case you would like to retry for example, if the network your device is on is not completely reliable, you may opt to retry a few times before reporting that the delete failed. To retry a delete specify the :retry action with this method. For example: RhoConnectClient.on_sync_delete_error('Product', object, :retry)

    Parameters

    • source_name : STRING

      The name of the source on the RhoConnect server.

    • objects : HASH

      An hash of one or more error objects. Structure of the objects hash is { id => { ‘attributes’ => { attribute => value }}}

    • action : SYMBOL

      Action to be performed on the error object(s).

      • :retry : STRING

        Push delete object operation to server again at next sync.

    Synchronous Return:

    • Void

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • Ruby: Rho::RhoConnectClient.on_sync_delete_error(STRING source_name, HASH objects, SYMBOL action)

    on_sync_update_error(STRING source_name, HASH objects, SYMBOL action, HASH rollback_objects)

    Perform an action on a record upon a sync update-error. The :retry action is similar to the :recreate action in the on_sync_create_error method. The :rollback action will roll back changes that are not accepted by the back-end. The record that will be rolled back to is the record(s) provided in the rollback_objects parameter. We recommend that the previous state of the record be saved in some way (preferably local such as cache) so that it can be provided upon update-error.

    Parameters

    • source_name : STRING

      The ORM model name. This is necessary for RhoConnect to know the model on which the action is to be performed.

    • objects : HASH

      A hash of one or more error objects. The structure of the objects hash is { id => { ‘attributes’ => { attribute => value }}}

    • action : SYMBOL

      Action to be performed on the objects specified in the objects hash.

      • :retry : STRING

        Push the update object operation to server again at next sync.

      • :rollback : STRING

        Write the rollback_objects to client database.

    • rollback_objects : HASH

      A hash of the attributes for the objects before a failed update and send by the server. Must be specified for :rollback action. Structure of the rollback_objects hash is { id => { ‘attributes’ => { attribute => value }}}

    Synchronous Return:

    • Void

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • Ruby: Rho::RhoConnectClient.on_sync_update_error(STRING source_name, HASH objects, SYMBOL action, HASH rollback_objects)

    search(HASH args, CallBackHandler callback)

    setNotification(STRING sourceName, CallBackHandler callback)

    The RhoConnectClient system uses notifications to provide information about the sync process to a Rhodes application. Notifications can be setup once for the duration of runtime or each time a sync is triggered. Once a sync is processing for a model, notifications are called with parameters containing sync process state. Your application can use this information to display different wait pages, progress bars, etc. setNotification will set notification for a model.

    Parameters

    • sourceName : STRING

      Source name for which notification will be enabled. Use ‘*’ to set notification for all models.

    • callback : CallBackHandler Mandatory

    Synchronous Return:

    • Void : this method also supports async callbacks - check the Callback tab for callback return parameters.

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.RhoConnectClient.setNotification(STRING sourceName, CallBackHandler callback)
      • Ruby: Rho::RhoConnectClient.setNotification(STRING sourceName, CallBackHandler callback)

    setObjectNotification(CallBackHandler callback)

    Replaces: set_objectnotify_url

    The RhoConnectClient can send a notification when a specific object on the current page has been modified. This is useful if you have frequently-changing data like feeds or time-lines in your application and want them to update without the user taking any action.

    Parameters

    • callback : CallBackHandler Mandatory

    Async Callback Returning Parameters: OBJECT

      • created : ARRAY

        Array of created objects.

      • updated : ARRAY

        Array of updated objects.

      • deleted : ARRAY

        Array of deleted objects.

    Synchronous Return:

    • Void : this method also supports async callbacks - check the Callback tab for callback return parameters.

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.RhoConnectClient.setObjectNotification(CallBackHandler callback)
      • Ruby: Rho::RhoConnectClient.setObjectNotification(CallBackHandler callback)

    set_pagesize(INTEGER size)

    Set the synchronization page size for the RhoConnectClient.

    Parameters

    • size : INTEGER

      Size of the RhoConnectClient synchronization page.

    Synchronous Return:

    • Void

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • Ruby: Rho::RhoConnectClient.set_pagesize(INTEGER size)

    set_pollinterval(INTEGER interval)

    Updates the RhoConnectClient poll interval.

    Parameters

    • interval : INTEGER

      Number of seconds for the poll interval. 0 disables polling-based synchronization (you may still use push-based-synchronization).

    Synchronous Return:

    • Void

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • Ruby: Rho::RhoConnectClient.set_pollinterval(INTEGER interval)

    set_ssl_verify_peer(BOOLEAN true_or_false)

    Enable or disable verification of RhoConnect SSL certificates.

    Parameters

    • true_or_false : BOOLEAN Default: true

      • true : BOOLEAN

        Enable verification of RhoConnect SSL certificates.

      • false : BOOLEAN

        Disable verification of RhoConnect SSL certificates.

    Synchronous Return:

    • Void

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • Ruby: Rho::RhoConnectClient.set_ssl_verify_peer(BOOLEAN true_or_false)

    set_syncserver(STRING server_url)

    Sets the RhoConnect server address and stores it in rhoconfig.txt. This will modify the URL set before running the app.

    Parameters

    • server_url : STRING

      The URL for the RhoConnect server.

    Synchronous Return:

    • Void

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • Ruby: Rho::RhoConnectClient.set_syncserver(STRING server_url)

    stopSync()

    Replaces: stop_sync

    Stops any sync operations currently in progress.

    There is a high potential of database corruption if this method is used during a sync. Do not do this unless you are planning on resetting your DB afterward.

    Synchronous Return:

    • Void

    Method Access:

    • Class Method: This method can only be accessed via the API class object.
      • JavaScript: Rho.RhoConnectClient.stopSync()
      • Ruby: Rho::RhoConnectClient.stopSync()

    Properties

    bulksyncState : INTEGER

    Set 0 to force bulk sync on next synchronization cycle. After sync is complete, bulksyncState will be set to 1.

    (Not currently supported in JavaScript.)

    Default: 1

    Property Access:

    • Class: This property can only be accessed via the API class object.
      • Ruby: Rho::RhoConnectClient.bulksyncState

    pageSize : INTEGER

    Page size for RhoConnectClient. Default size is 2000.

    Property Access:

    • Class: This property can only be accessed via the API class object.
      • JavaScript: Rho.RhoConnectClient.pageSize
      • Ruby: Rho::RhoConnectClient.pageSize

    pollInterval : INTEGER

    Sync poll interval in seconds. Setting this to 0 will disable polling-based sync. Sync process will be triggered automatically according to this setting.

    Default: 60

    Property Access:

    • Class: This property can only be accessed via the API class object.
      • JavaScript: Rho.RhoConnectClient.pollInterval
      • Ruby: Rho::RhoConnectClient.pollInterval

    showStatusPopup : BOOLEAN

    Enable or disable show status pop-up.

    Default: true

    Property Access:

    • Class: This property can only be accessed via the API class object.
      • JavaScript: Rho.RhoConnectClient.showStatusPopup
      • Ruby: Rho::RhoConnectClient.showStatusPopup

    sslVerifyPeer : BOOLEAN

    Enable or disable verification of RhoConnect ssl certificates, true by default.

    Default: true

    Property Access:

    • Class: This property can only be accessed via the API class object.
      • JavaScript: Rho.RhoConnectClient.sslVerifyPeer
      • Ruby: Rho::RhoConnectClient.sslVerifyPeer

    syncServer : STRING

    Sync server URL.

    Property Access:

    • Class: This property can only be accessed via the API class object.
      • JavaScript: Rho.RhoConnectClient.syncServer
      • Ruby: Rho::RhoConnectClient.syncServer

    userName : STRING Read Only

    Current username of the RhoConnectClient session if isLoggedIn is true, otherwise returns the last logged in username.

    Property Access:

    • Class: This property can only be accessed via the API class object.
      • JavaScript: Rho.RhoConnectClient.userName
      • Ruby: Rho::RhoConnectClient.userName

    Examples

    Sync Authentication

    In your controller call login.

    Rho.RhoConnectClient.login('john','password',function(result){
       loginCallback(result);
    });
                              
    RhoConnectClient.login(
      @params['login'],
      @params['password'],
      url_for(:action => :login_callback)
    )
                              

    When RhoConnectClient.login completes, the callback declared is executed and receives parameters including success or failure and error messages (if any).

    // Error codes:
    // ERR_NONE = 0
    // ERR_NETWORK = 1
    // ERR_REMOTESERVER = 2
    // ERR_RUNTIME = 3
    // ERR_UNEXPECTEDSERVERRESPONSE = 4
    // ERR_DIFFDOMAINSINSYNCSRC = 5
    // ERR_NOSERVERRESPONSE = 6
    // ERR_CLIENTISNOTLOGGEDIN = 7
    // ERR_CUSTOMSYNCSERVER = 8
    // ERR_UNATHORIZED = 9
    
    function loginCallback(result) {
      var errorCode = parseInt(result.error_code);
      var errorMessage = result.error_message;
      if(errorCode === 0 {
        // process success
      } else {
        // process error with errorMessage
      }
    }
                                
    # Error codes:
    # ERR_NONE = 0
    # ERR_NETWORK = 1
    # ERR_REMOTESERVER = 2
    # ERR_RUNTIME = 3
    # ERR_UNEXPECTEDSERVERRESPONSE = 4
    # ERR_DIFFDOMAINSINSYNCSRC = 5
    # ERR_NOSERVERRESPONSE = 6
    # ERR_CLIENTISNOTLOGGEDIN = 7
    # ERR_CUSTOMSYNCSERVER = 8
    # ERR_UNATHORIZED = 9
    
    def login_callback
      error_code = @params['error_code'].to_i
      if error_code == Rho::RhoError::ERR_NONE
        # run sync if we were successful
        WebView.navigate Rho::RhoConfig.options_path
        RhoConnectClient.doSync
      else
        if error_code == Rho::RhoError::ERR_CUSTOMSYNCSERVER
          @msg = @params['error_message']
        end
    
        if not @msg or @msg.length == 0
          @msg = Rho::RhoError.new(error_code).message
        end
    
        WebView.navigate(
          url_for(:action => :login, :query => {:msg => @msg})
        )
      end
    end
                                
    Notifications

    First, assign a sync notification for the Account model:

    function syncNotify(params) {
      // handle notifications...
    }
    Rho.RhoConnectClient.setNotification('Account', syncNotify);
    
                                
    RhoConnectClient.setNotification(
      'Account',
      url_for(:action => :sync_notify),
      "sync_complete=true"
    )
                                

    Which is the same as:

    function syncNotify() {
      // handle notifications...
    }
    Account.setNotification(syncNotify);
    
                                
    Account.setNotification(
      url_for(:action => :sync_notify),
      "sync_complete=true"
    )
                                

    You can also set a notification for all models:

    function syncNotify(params) {
      // handle notifications...
    }
    Rho.RhoConnectClient.setNotification('*', syncNotify);
    
                                
    RhoConnectClient.setNotification(
      '*',
      url_for(:action => :sync_notify),
      "sync_complete=true"
    )
                                
    Object notifications

    To use object notifications, first set the notification callback in application.rb#initialize.

    class AppApplication < Rho::RhoApplication
        def initialize
            super
    
            RhoConnectClient.setObjectNotification(
                url_for(
                    :controller => "Product",
                    :action => :sync_object_notify
                )
            )
        end
    end
                                

    Next, in your controller action that displays the object(s), add the object notification by passing in a record or collection of records:

    function syncObjectNotified(params) {
      // handle notifications...
    }
    
    var product = Product.find('first');
    
    Rho.RhoConnectClient.addObjectNotify('Product', product.id);
    
                                
    class ProductController < Rho::RhoController
      # GET /Product
      def index
        @product = Product.find(:first)
    
        RhoConnectClient.addObjectNotify('Product', @product.id)
        render
      end
    
      # ...
    
      def sync_object_notified
        # process notification data ...
    
        # refresh the current page
        WebView.refresh
        # or call System.execute_js to update part of the page
      end
    end
    
                                
    Handling Errors

    Here we will set a notification and log an error code 1 or ERR_NETWORK:

    function syncNotify(result) {
      var errorCode = parseInt(result.error_code);
      var errorMessage = result.error_message;
      if(errorCode === 1) {
        console.log("We received a network error: " + errorMessage);
        return;
      }
    }
    Rho.RhoConnectClient.setNotification('*', syncNotify);
    
                                
    RhoConnectClient.setNotification(
      '*',
      url_for(:action => :sync_notify),
      "sync_complete=true"
    )
    
    # In your controller:
    def sync_notify
      error_code = @params['error_code'].to_i
      error_message = @params['error_message']
      if error_code == Rho::RhoError::ERR_NETWORK
        puts "We received a network error: " + error_message 
      end
    end
    
    
                                
    Using search (Ruby Only)

    First, call search from your controller action:

    def search
      page = @params['page'] || 0
      page_size = @params['page_size'] || 10
      RhoConnectClient.search(
        {
          'Contact',
          :from => 'search',
          :search_params => {
            :FirstName => @params['FirstName'],
            :LastName => @params['LastName'],
            :Company => @params['Company']
          },
          :offset => page * page_size,
          :max_results => page_size
        }
        url_for(:action => :search_callback)
      )
      render :action => :search_wait
    end
    
                                

    The search_params will be forwarded to your callback so you can update the view with the results:

    def search_callback
      status = @params["status"]
      if (status and status == "ok")
      WebView.navigate(
        url_for(
          :action => :show_page,
          :query => @params['search_params']
        )
      )
      else
        render :action => :search_error
      end
    end
    
    def show_page
      @contacts = Contact.find(
        :all,
        :conditions => {
        {
          :func => 'LOWER',
          :name => 'FirstName',
          :op => 'LIKE'
        } => @params[:FirstName],
        {
          :func => 'LOWER',
          :name=>'LastName',
          :op=>'LIKE'
        } => @params[:LastName],
        {
          :func=>'LOWER',
          :name=>'Company',
          :op=>'LIKE'
        } => @params[:Company],
        },
        :op => 'OR',
        :select => ['FirstName','LastName', 'Company'],
        :per_page => page_size,
        :offset => page * page_size
      )
      render :action => :show_page
    end
    
                                

    Remarks

    Notification Callback Parameters

    When the notification is called, it will receive a variable called @params, just like a normal Rhodes controller action.

    Common Parameters

    These parameters are included in all notifications.

    • source_id – The id of the current model that is synchronizing.
    • source_name – Name of the model (i.e. “Product”)
    • sync_type – Type of sync used for this model: “incremental” or “bulk”
    • status – Status of the current sync process. See below for the possible values:

    In the following sections we cover the different status values and parameters available with each status.

    status: “in_progress” – incremental sync progress

    • total_count – Total number of records that exist for this RhoConnect source.
    • processed_count – Number of records included in the sync page.
    • cumulative_count – Number of records the RhoConnectClient has processed so far for this source.

    status: “in_progress” – bulk sync progress

    • bulk_status – The state of the bulk sync process:

      • start – Bulk sync has started for a specific partition
      • download – Bulk sync file download has started
      • change_db – New bulk sync database change has started
      • blobs – Bulk sync blob files have started to download
      • ok – Current partition has completed
      • complete – All partitions have completed
    • partition – Current bulk sync partition.

    status: “error”

    • error_code – HTTP response code of the RhoConnect server error: 401, 500, 404, etc.
    • error_message – Response body (if any)
    • server_errors – Hash of Type objects of RhoConnect adapter error (if exists):
      • login-error – An error in adapter login method
      • query-error – An error in adapter query method
      • create-error – An error in adapter create method
      • update-error – An error in adapter update method
      • delete-error – An error in adapter delete method
      • logoff-error – An error in adapter logoff method

    Each error contains a ‘message’ key with the error message.

    Ruby Example:

    @params["server_errors"]["query-error"]["message"] 
    #=> "Error connecting to backend server: http://rhostore.herokuapp.com"
    

    JavaScript Example:

    params.server_errors["query-error"].message
    //=> "Error connecting to backend server: http://rhostore.herokuapp.com"
    

    Handling ‘create-error’

    “create-error” is a unique situation that needs to be handled in your sync callback. See RhoConnectClient.on_sync_create_error() for more details.

    status: “complete”

    This status returns only when the sync run is complete (all partitions are done synchronizing).

    status: “schema-changed”

    This is present if a FixedSchema model has changed during the current sync run. A new bulk sync run should be triggered (by setting bulksyncState) and the user should be alerted in the UI.

    Backround Sync on iOS

    On iOS, if the application is backgrounded, it will be suspended. This also means if a current sync is in progress, it will immediately terminate. To prevent this behavior, set ‘finish_sync_in_background’ to ‘1’ in rhoconfig.txt. When set to ‘1’, the RhoConnectClient will attempt to finish synchronization before the application fully suspends.