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)

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()

    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 timelines 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)

    stopSync()

    Replaces: stop_sync

    Stops any sync operations currently in progress.

    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:

    • Instance: This property can be accessed via an instance object of this class:
      • myObject.bulksyncState

    pageSize : INTEGER

    Page size for RhoConnectClient. Default size is 2000.

    Property Access:

    • Instance: This property can be accessed via an instance object of this class:
      • myObject.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:

    • Instance: This property can be accessed via an instance object of this class:
      • myObject.pollInterval

    showStatusPopup : BOOLEAN

    Enable or disable show status popup.

    Default: true

    Property Access:

    • Instance: This property can be accessed via an instance object of this class:
      • myObject.showStatusPopup

    sslVerifyPeer : BOOLEAN

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

    Default: true

    Property Access:

    • Instance: This property can be accessed via an instance object of this class:
      • myObject.sslVerifyPeer

    syncServer : STRING

    Sync server URL.

    Property Access:

    • Instance: This property can be accessed via an instance object of this class:
      • myObject.syncServer

    userName : STRING Read Only

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

    Property Access:

    • Instance: This property can be accessed via an instance object of this class:
      • myObject.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 SyncEngine 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.onSyncCreateError() 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.